Django注释引发AttributeError'对象没有属性'

时间:2015-02-03 14:12:08

标签: django django-queryset

您好我正在尝试使用django的注释,我认为我做的一切都很好,但我必须遗漏一些东西,因为我收到了属性错误

以下是我的模特

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 个答案:

答案 0 :(得分:6)

Queryset方法不会修改现有的查询集,它们会返回一个新的查询集。因此,您的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')
相关问题