Django按问题过滤答案- group by with返回一个值列表



我有三个表,外键部分,问题和答案:

class Question(models.Model):
questions = models.TextField() 
section = models.ForeignKey(
Section, 
on_delete=models.CASCADE,
related_name = 'section_question')
objects = QuestionManagers()
class Answer(models.Model):
answers = models.CharField(max_length=140)
answer_is = models.BooleanField(default=False)
questions = models.ForeignKey(
Question, 
on_delete=models.CASCADE,
related_name = 'question_answer')

我想做一个查询,过滤每个问题的答案,并尝试了各种方法,但无法。

class QuestionManagers(models.Manager):
def question_by_section(self, section):
if section:
return self.filter(
section__slug=section.slug,
).values()
def answer_by_question(self, section):
if section:
return self.filter(
section__slug=section.slug,
).values(
'questions'
).values(
'question_answer__answers'
)

使用question_by_section,您可以过滤问题,但现在我错过了答案。

如果您想要按部分过滤答案,您可以定义一个AnswerManager吗?

也许像这样:

class AnswerManager(models.Manager):
def answer_by_section(self, section):
if section:
return self.filter(questions__section__slug=section.slug)
class Answer(models.Model):
...
objects = AnswerManager()

可以使用annotate()。如果您需要按另一个值分组,请将其添加到较早的values()子句中。

ArrayAgg(PostgreSQL)返回一个值列表,包括空值,连接成一个数组。

from django.db.models import Count
from django.contrib.postgres.aggregates import ArrayAgg
class QuestionManagers(models.Manager):
...
def answer_by_question(self, section):
if section:
return self.filter(
section__slug=section.slug,
).values('questions').annotate(Count('question_answer'), arr=ArrayAgg('question_answer__answers'))

相关内容

  • 没有找到相关文章

最新更新