Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

Django Subquery in SQL FROM part

The Django Documentation shows how to create a subquery in the SELECT part of the SQL query, but how to create a subquery in the FROM part? i.e:

SELECT    ...
FROM (
    SELECT    ...
    FROM      ...
    WHERE     ...
    GROUP BY  ...
)
WHERE     ...
ORDER BY  ...

Here is a specific example in case this helps, but if you can answer the general question above without this example, please do.


If we have the models:

class MyModel(models.Model):
    field1 = models.CharField()
    other_model = models.ForeignKey(OtherModel)


class OtherModel(models.Model):
    field2 = models.CharField()
    field3 = models.CharField()
    active = models.BooleanField()

Let's say I want to count for each my_model.field1 value the number of OtherModel.field3 values where there are some instances my_model, other_model with my_model.other_model == other_model and other_model.active == True So I would like to have a subquery where I group by field1 and field3 and count the actives:

sub_query = MyModels.values('field1', 'othermodel__field3').annotate(actives=Count(Case(When(othermodel__active=True, then=1))))

And then a main query where I group the results of the first query by field1 and count them per group:

main_query = qub_query.values('field1').annotate(active_combinations=Count('field1', filter=Q(actives__gt=0)))

But this is interpreted in a different way and does not work like this.

question from:https://stackoverflow.com/questions/65906299/django-subquery-in-sql-from-part

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...