我有以下QuerySet。
from myapp.events.models import Event
from myapp.surveys import QuestionFocus
from django.conf import settings
event = Event.objects.get(pk=12)
survey = event.surveys.get(
template=settings.SURVEY_POST_EVENT
).questions.filter(
focus=QuestionFocus.RECOMMENDATION_TO_FRIENDS,
answers__answer="9"
).prefetch_related("answers")
survey.first().answers.all()
现在我只希望有两个答案(9)。但是,完全不考虑我的过滤器请求。看到我做错了吗?
>>> <QuerySet [Answer: 2, Answer: 9, Answer: 9, Answer: 10]>
答案模型:
class Answer(TimeStampedModel):
question = models.ForeignKey(
"surveys.Question", on_delete=models.CASCADE, related_name="answers"
)
response = models.ForeignKey(
"Response", on_delete=models.CASCADE, related_name="answers"
)
answer = models.TextField(verbose_name=_("Answer"))
choices = models.ManyToManyField(
"surveys.AnswerOption", related_name="answers", blank=True
)
最佳答案
根据您当前的设计,一个Question
实例可以与许多Answer
实例相关。因此,survey.first()
返回第一个过滤的Question
,而.answers.all()
会返回所有相关的答案实例。
您的answers__answer="9"
过滤器运行正常;由于具有这种关系,它将仅显示包含Question
且answers
字段值为answer
的9
实例。
如果许多问题可以有一个共同的答案,也许您想在Question
和Answer
之间建立一对一的关系,或者在Question
和Answer
之间建立多对一的关系。
关于python - Django:QuerySet过滤器无法按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58781824/