Option 1:
Although a group_by()
does not exist in Django, you can try and work around on retrieving the most recently closed invoice for each user by utilizing latest()
method and filter for a user as well:
previous_invoices = Invoice.objects.filter(user=my_user, is_open=False)
.latest('created')
For older versions of Django were latest()
does not exist, the query will look like this:
previous_invoices = Invoice.objects.filter(user=my_user, is_open=False)
.order_by('-created')[0]
Option 2:
UPDATE: I have since then added a Q&A style example here: How to execute a GROUP BY ... COUNT or SUM in Django ORM? that shows how to simulate a GROUP BY
operation on Django ORM.
If you absolutely want to create the effects of a group_by
, then you can create one manually as shown in the accepted answer here: Django GROUP BY field value.
Use .values_list()
with flat=True
to get a list of the existent values in your database (if you don't know them beforehand). Also use .distinct()
to eliminate duplicate values as we do not care for those:
value_list = MyModel.objects.values_list(
'interesting_field', flat=True
).distinct()
Now iterate through value_list
and fill your dictionary:
group_by_value = {}
for value in value_list:
group_by_value[value] = MyModel.objects.filter(interesting_field=value)
Now group_by_value
dictionary contains as keys the distinct values
in your interesting_field
and as values the queryset objects, each
containing the entries of MyModel
with interesting_field=a value
from value_list
.
Note:
There exists this library django-group-by which claims to add a group_by()
on Django you may want to check.