Subquery in django ORM

2019-08-27 11:38发布

I have a table with next columns:

  • key
  • time
  • value

And I need to have a query like that:

SELECT
  "time",
  SUM("value")
FROM (
  SELECT
    "key",
    django_trunc_datetime("time"),
    AVG("value")
  FROM my_table
  GROUP BY "key", django_trunc_datetime("time")
)
GROUP BY "time"

Is it possible in Django ORM? Maybe with some fake model based on the subquery?

Thanks

UPDATED: Looks like I have to create five database views (because there are Hour/Day/Week/Month/Year arguments for the django_trunc_datetime) but it can have a bad performance because in this case, I can't do the previous filtering. :(

I also thought about SQLAlchemy but it doesn't have universal datetime truncate function

SOLUTION

The solution with DjangoORM (not completed solution but illustrate the idea)

class TheApp(models.Model):
    a = models.DateTimeField()
    b = models.IntegerField()

class B(models.Model):
    class Meta:
        managed = False

    c = models.DateTimeField()
    d = models.IntegerField()

TheApp.objects.create(a=datetime.now(), b=4)
TheApp.objects.create(a=datetime.now(), b=5)
TheApp.objects.create(a=datetime.now(), b=7)

q1 = TheApp.objects.annotate(c=F('b'), d=Max('a')).values('c', 'd', 'id').query
q1.group_by = ('c',)
q2 = B.objects.annotate(a=F('c') * 2, b=Max('d')).values('a', 'b', 'id').query
q2.group_by = ('a',)

q3 = str(q2).replace('theapp_b', 'sub').replace('FROM "sub" ', f'FROM ({q1}) AS "sub" ')
print(q3)
print(list(B.objects.raw(q3)))

The solution I have chosen:

Use SQLAlchemy via aldjemy

0条回答
登录 后发表回答