[Django]-Return object when aggregating grouped fields in Django

0👍

Alright, I think this one might actually work for you. It is based upon an assumption, which I think is correct.

When you create your model object, they should all be unique. It seems highly unlikely that that you would have two events on the same date, in the same location of the same type. So with that assumption, let’s begin: (as a formatting note, class Names tend to start with capital letters to differentiate between classes and variables or instances.)

# First you get your desired events with your criteria.
results = Event.objects.values('location', 'type').annotate(latest_date=Max('date'))

# Make an empty 'list' to store the values you want.
results_list = []

# Then iterate through your 'results' looking up objects
# you want and populating the list.
for r in results:
    result = Event.objects.get(location=r['location'], type=r['type'], date=r['latest_date'])
    results_list.append(result)

# Now you have a list of objects that you can do whatever you want with.

You might have to look up the exact output of the Max(Date), but this should get you on the right path.

Leave a comment