Advanced Annotate

33 views
Skip to first unread message

Paolo C.

unread,
Sep 14, 2015, 8:41:55 PM9/14/15
to Django users

I've posted this issue on Stackoverflow

Given this model:

from django.db import models


class Post(models.Model):
    text = models.CharField(max_length=255)


class Comment(models.Model):
    text = models.CharField(max_length=255)
    needs_attention = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    post = models.ForeignKey(Post)

I can annotate the list of posts with:

Post.objects.annotate(last_comment_date=Max('comment__created_at'))

to know the last_comment_date, how to annotate to set a value for last_comment_needs_attention?

How can obtain details from the last comment when listing ll posts?

Thanks!

Carsten Fuchs

unread,
Sep 16, 2015, 9:57:38 AM9/16/15
to django...@googlegroups.com
Hi Paolo,

Am 15.09.2015 um 00:32 schrieb Paolo C.:
> How can obtain details from the last comment when listing ll posts?

If I understood your question correctly -- I recently had the same question, see
https://groups.google.com/d/msg/django-users/adRe2_BWMz0/G71BVUEI_7oJ for details.

It seems that the so far best answer is described at
http://blog.roseman.org.uk/2010/08/14/getting-related-item-aggregate/

Best regards,
Carsten

Paolo C.

unread,
Sep 16, 2015, 4:52:29 PM9/16/15
to Django users
Hi Carsten,

my problem is slightly different, in your example you wanted to annotate for example the max_book price, I need to annotate not only the price but also which is the book that has that max value.


Thanks

Carsten Fuchs

unread,
Sep 17, 2015, 12:31:43 PM9/17/15
to django...@googlegroups.com
Hi Paolo,

Am 16.09.2015 um 22:52 schrieb Paolo C.:
> [...], I need to annotate not only the price but also which is the book that
> has that max value.

Isn't that exactly what I was wondering about, too?

"1) Is there a way to annotate each Store object with the actual Book objects related
to the minimum and maximum prices?"

Best regards,
Carsten
Reply all
Reply to author
Forward
0 new messages