Skip to content
Advertisement

How to Join Subqueries in Django ORM

I’m a beginner Django and I have been stuck on the following problem for a while.

The basic thing I would like to achieve is that when client makes a GET list api request with a time period parameter (say 3 months) then the server would return an aggregation of the current 3 months data and also show an extra field comparing the difference with previous 3 months.

I have models as:

JavaScript

The sample output I would like to get is something like:

JavaScript

The raw SQL query (in Postgres) is quite simple as below but I’m really struggling on how to make this work in Django.

JavaScript

What I have Tried

  • I don’t think using the raw query (in the form I indicated above) as works in my case b/c I need it to handle filters (the GET request from client can have other query params from which server will handle additional filters)
  • I tried to union the current and previous querysets and then groupby, but it seems that this is not supported:
JavaScript

django.db.utils.NotSupportedError: Calling QuerySet.annotate() after union() is not supported.

Advertisement

Answer

You could try this one.

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