简体   繁体   中英

How to annotate the Max of a related object to a Django queryset

I have a Django website where users can make groups, and then write replies under the said groups.

Simply put:

class Group(models.Model):
    owner = models.ForeignKey(User)        
    #some attributes

class Reply(models.Model):
    text = models.TextField(validators=[MaxLengthValidator(500)])
    writer = models.ForeignKey(User)

For a given user, I want to find all groups that she either made, or ever replied under (even if once). Furthermore, from all such groups, I want to extract the ID of the most recent reply - whether made by the user herself, or by someone else.

To accomplish the above, I have tried:

groups = Group.objects.filter(Q(owner=self.request.user)|Q(reply__writer=self.request.user)).distinct()
ids = groups.annotate(max_reply=Max('reply__id')).values_list('max_reply', flat=True)

This doesn't work - in ids , I only get the most recent reply written by self.request.user herself, not the absolute most recent reply (written by anyone) under each group. I find that weird because seemingly, this ought to work, no? Maybe I'm referencing the reverse foreignkey incorrectly.

Can you help me fix this, or suggest an alternative?

The following is how I'm currently accomplishing it. I assign the ids of all relevant groups to groups . I find the ids of max replies under each and assign them to replies . Finally, I construct a queryset around 60 such replies, assigning that to replies_qs .

groups = Group.objects.filter(Q(owner=self.request.user)|Q(reply__writer=self.request.user)).distinct().values_list('id', flat=True)
replies = Reply.objects.filter(which_group__in=groups).values('which_group_id').annotate(Max('id')).values_list('id__max', flat=True)
replies_qs = Reply.objects.filter(id__in=replies)[:60]

This is 3 DB accesses, would prefer to do it in less, if someone has a suggestion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM