简体   繁体   中英

Django - Select MAX of field of related query set

Say if I have models:

class User(models.Model):
    name = ...
    dob = ...

class Event(models.Model):
    user = models.ForeignKey(User, ...)
    timestamp = models.DateTimeField()

And I want to query all Users and annotate with both Count of events and MAX of Events.timestamp

I know for count I can do:

Users.objects.all().annotate(event_count=models.Count('event_set'))

But how do I do max of a related queryset field? I want it to be a single query, like:

SELECT Users.*, MAX(Events.timestamp), COUNT(Events) FROM Users JOIN Events on Users.id = Events.user_id

You could use Query Expressions to achieve that. You might have to play around with the foreign key related name depending on your code, but it would result in something looking like this:

from django.db.models import Count, F, Func,

Users.objects.all().annotate(
    event_count=Count('event_set'), 
    max_timestamp=Func(F('event_set__timestamp'), function='MAX')
)

You can try an aggregate query for this as follows:

from django.db.models import Max

Users.objects.all().aggregate(Max('Events.timestamp'))

See details for the above code in Django documentation here

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