Django注释引发AttributeError 'object has no attribute'错误

4

你好,我正在尝试使用Django的annotate功能,我认为我做得很好,但是我一定漏掉了什么,因为我遇到了Attribute Error错误。

这是我的模型:

class Operation(models.Model):
    ...

class Message(models.Model):
    operation = models.ForeignKey(Operation)
    sent_on = models.DateTimeField(auto_now_add=True)
    ...

以下是我尝试做的事情:

    ops = Operation.objects.filter(...)
    ops.annotate(last_message=Max('message__sent_on'))
    ops.order_by('-last_message')

    print ops[0].last_message

我正在获得

AttributeError at ...
'Operation' object has no attribute 'last_message'

请注意,如果我将注释更改为ops.annotate(last_message=Max('whatever')),我会收到FieldError,因此之前的语法是正确的...但为什么我无法访问last_message字段呢?

我正在使用django 1.6.10

谢谢!

1个回答

10

查询集方法不会直接修改现有的查询集,它们会返回一个新的查询集。因此,你的annotateops调用实际上并没有做任何事情,因为它们创建了一个新的查询集,然后立即被丢弃。

你需要重新分配调用的结果:

ops = Operation.objects.filter(...)
ops = ops.annotate(last_message=Max('message__sent_on'))
ops = ops.order_by('-last_message')

或者一次性完成:

ops = Operation.objects.filter(
    ...
).annotate(
    last_message=Max('message__sent_on')
).order_by('-last_message')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接