简体   繁体   English

Django的;按相关对象计数查询数据库

[英]Django; Querying the Database By Counts Of Related Objects

I have a question model: 我有一个问题模型:

class Question(models.Model):
....

and an answer model related to it: 和一个与之相关的答案模型:

class Answer(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)

I want to filter out all the questions with no answers. 我想过滤掉所有没有答案的问题。 How can I do that in the view? 我怎么能在视图中这样做?

below query get all questions that not related answers: 以下查询获取所有无关答案的问题:

Question.objects.annotate(answer_count=Count('answer')).filter(answer_count=0)

Update: 更新:
You can behave by every annotate parameters same as real model fields in filter method, for example all questions that have more than three answer: 您可以按照与过滤方法中的实际模型字段相同的每个annotate参数来执行操作,例如,所有具有三个以上答案的问题:

Question.objects.annotate(answer_count=Count('answer')).filter(answer_count__gt=3)

NOTE: 注意:
How annotate method works? 注释方法如何工作?
In back of all relational-db ORMs transactions handle by SQL language, and SQL prefer some extra functions that made more flexibility in many actions, specificly in SELECT statement, for sample some times we needs average or count of columns in multiples rows, see below: 在所有关系-db ORM事务的后面,SQL语言处理事务,并且SQL更喜欢一些额外的函数,这些函数在许多操作中具有更大的灵活性,特别是在SELECT语句中,对于样本,我们需要多次行的平均值或列数,请参见下文:

SELECT count(*) from my_table;

if upper count function not prefered, we must fetch all records first, and in another step calculate length of results, this method is difficult and have many pros. 如果不countcount函数,我们必须首先获取所有记录,而在另一步计算结果长度,这种方法很难并且有很多优点。
Django ORM prefered equal SQL usable functions that only must using in annotate funtion and translate to SQL before run. Django ORM倾向于使用相同的SQL可用函数,这些函数只能在注释函数中使用并在运行之前转换为SQL。

More info aboute annotate method 更多信息aboute annotate方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM