django - Getting Posts and its last comment in a single queryset -


let's assume i've classic blog post multiple related comments model. i'm trying list of posts each annotated last comment (or @ least single field it).

the closest i've gotten via:

post.objects.annotate(last_comment=f('comment__text')) 

but returns body first commend, , explicitly want last.

am missing pretty obvious? or there smart way of doing i'm failing see?

if want retrieve latest comment, might want specify ordering on meta

something this:

class comment(models.model):    ...    class meta:        ordering = ('-created_at', ) #or id, or whatever 

then, query

post.objects.annotate(last_comment=f('comment__text')) 

would retrieve latest post.

specifying ordering (in case) equivalent of saying comments.objects.order_by('-created_at'), , work, want latest comment.

one caveat here though is, ordering applied default everywhere comments retrieved. also, has database implications ordering not free


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -