1

Where can I find some information about building a query like this:

select
  SomeField1,
  (select count(distinct SomeField2) from SomeTable where SomeCondition) as SomeField3
from
  SomeTable2
where
  SomeCondition2

using Django ORM? It's probably in the Django documentation somewhere but I can't find it.

4

3 回答 3

0

Django's ORM is meant to execute queries on a per-model basis and its relational data (i.e ForeignKey, ManyToManyRelationship, ...). Your example shows that you need two results at the same time from two unrelated models. AFAIK, there is no way to do it apart from doing it separately

count = SomeTable.objects.filter(SomeCondition).distinct(SomeField2).count()
somefield1 = SomeTable2.objects.filter(SomeCondition2)

However there are a few ways you can achieve it if you really need to do it but I would not recommend them:

Django Queryset across Models?

Query field across multiple django models

于 2012-10-04T11:10:19.777 回答
0

What's the relationship of your two tables?

I guess you need the count,there is a code snippet without check,

SomeModel2.objects.annotate(new_field=Count('SomeField2', 
    distinct=True)).filter(condition=condition,
    another_condition=condition2).values('new_field', 'Somefield1')

See https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate and How to sort by annotated Count() in a related model in Django for more details.

于 2012-10-04T11:14:53.880 回答
0

Since your question is specifically where you can find this information, take a look at Aggregation | Django docs - it should help you achieve some of what you're trying here (specifically, count).

However querying unrelated tables together is not exactly a common thing to do. You would be better off making separate queries and relating the returned data together manually, since your database will split up that query anyway.

In your case, I would recommend you make raw SQL queries on your database if you have to run that query,

于 2012-10-04T11:18:46.100 回答