gpt4 book ai didi

反向多对多关系的Django查询集

转载 作者:行者123 更新时间:2023-12-04 02:44:54 25 4
gpt4 key购买 nike

在给定 FaqTopic id 的情况下,我试图获得已回答有关该主题问题的受访者的结果集。我假设这至少需要两个查询,但我不完全确定如何去做。我的模型大致如下所示:

class FaqTopic(models.Model):
name = models.CharField(max_length=50)

class Respondant(models.Model):
name = models.CharField(max_length=50)

class Answer(MediaReady):
text = models.TextField( blank=True )
respondant = models.ForeignKey( Respondant, blank=True, null=True )

class Question(MediaReady):
text = models.CharField( max_length=255, blank=True )
answers = models.ManyToManyField( Answer, blank=True, null=True )
topic = models.ForeignKey( FaqTopic, blank=True, null=True )

我可以这样做:

topic = FaqTopic.objects.get(pk=topic_id)
questions = topic.question_set.all()

然后遍历每个问题并构建一组独特的回答者。但这看起来很难看。

最佳答案

您可以在一次查询中完成。这将为您提供回答了特定主题问题的受访者。

respondants = Respondant.objects.filter(answer__question__topic__name = name)

或者如果你有一个topic对象,

respondants = Respondant.objects.filter(answer__question__topic = topic)

您可以在 lookups that span relationships here 上阅读更多内容

关于反向多对多关系的Django查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19038375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com