Skip to content
Advertisement

Django ORM filter multiple fields using ‘IN’ statement

So I have the following model in Django:

My goal is to have all the tuples grouped by the member with the most recent date. There are many ways to do it, one of them is using a subquery that groups by the member with max date_time and filtering member_loyalty with its results. The working sql for this solution is as follows:

Another way to do this would be by joining with the subquery.

How could i translate this on a django query? I could not find a way to filter with two fields using IN, nor a way to join with a subquery using a specific ON statement.

I’ve tried:

But it starts grouping by the loyalty_value.

Also tried building the subquery, but cant find how to join it or use it on a filter:

Also, I am using Mysql so I can not make use of the .distinct(‘param’) method.

Advertisement

Answer

This is a typical greatest-per-group query. Stack-overflow even has a tag for it.

I believe the most efficient way to do it with the recent versions of Django is via a window query. Something along the lines should do the trick.

Update: This actually won’t work, because Window annotations are not filterable. I think in order to filter on window annotation you need to wrap it inside a Subquery, but with Subquery you are actually not obligated to use a Window function, there is another way to do it, which is my next example.

If either MySQL or Django does not support window queries, then a Subquery comes into play.

If event Subqueries are not available (pre Django 1.11) then this should also work:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement