Hi I'm trying to use django's annotate and I think I'm doing everything ok but I must be missing something because I'm getting an Attribute Error
Here are my models
class Operation(models.Model):
...
class Message(models.Model):
operation = models.ForeignKey(Operation)
sent_on = models.DateTimeField(auto_now_add=True)
...
And here is what I'm trying to do:
ops = Operation.objects.filter(...)
ops.annotate(last_message=Max('message__sent_on'))
ops.order_by('-last_message')
print ops[0].last_message
And I'm getting
AttributeError at ...
'Operation' object has no attribute 'last_message'
Notice that if I change the annotate to ops.annotate(last_message=Max('whatever'))
I get a FieldError
, so the previous syntax was right... but why then can't I access the last_message field?
I'm using django 1.6.10
Thanks!
Queryset methods do not modify the existing queryset in place, they return a new one. So your annotate
and ops
calls are in fact not actually doing anything, as they create a new queryset and then it is immediately thrown away.
You need to reassign the result of the calls:
ops = Operation.objects.filter(...)
ops = ops.annotate(last_message=Max('message__sent_on'))
ops = ops.order_by('-last_message')
or just do it in one go:
ops = Operation.objects.filter(
...
).annotate(
last_message=Max('message__sent_on')
).order_by('-last_message')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With