Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM: Group by and Max

Tags:

I have a model that looks like this:

Requests: user, req_time, req_text 

In the DB, the records can look like this:

id, user_id, req_time, req_text 1     1      TIMESTAMP  YES 2     1      TIMESTAMP  NO 3     2      TIMESTAMP  YES 

etc.

How do I write a Django ORM query that: groups the Requests by user, filters the Requests based on req_text, and also, select the max id of the resulting result set. So for each user, I will return one row which matches the filter condition and also has the greatest id.

like image 896
jeffreyveon Avatar asked Aug 04 '11 11:08

jeffreyveon


People also ask

What is difference between annotate and aggregate in Django?

Unlike aggregate() , annotate() is not a terminal clause. The output of the annotate() clause is a QuerySet ; this QuerySet can be modified using any other QuerySet operation, including filter() , order_by() , or even additional calls to annotate() .

What is __ in Django ORM?

Django Field Lookups Managers and QuerySet objects comes with a feature called lookups. A lookup is composed of a model field followed by two underscores ( __ ) which is then followed by lookup name.

What is OuterRef Django?

to Django users. According to the documentation on models. OuterRef: It acts like an F expression except that the check to see if it refers to a valid field isn't made until the outer queryset is resolved.

What is aggregation in Django?

Aggregate Aggregate generate result (summary) values over an entire QuerySet. Aggregate operate over the rowset to get a single value from the rowset. (For example sum of all prices in the rowset). Aggregate is applied on entire QuerySet and it generate result (summary) values over an entire QuerySet.


1 Answers

from django.db.models.aggregates import Max  request_values = Requests.objects.filter(req_text='YES') \                  .values('user') \                  .annotate(max_id=Max('id')) 

Then request_values will look like this:

[     {'user': 1, 'max_id': 1},     {'user': 2, 'max_id': 4},     {'user': 3, 'max_id': 5},     {'user': 4, 'max_id': 12},     ... ] 
like image 152
Botond Béres Avatar answered Sep 20 '22 23:09

Botond Béres