gpt4 book ai didi

python - Django - 连接两个模型的最佳实践

转载 作者:行者123 更新时间:2023-12-01 05:38:30 25 4
gpt4 key购买 nike

我正在开发一个项目,允许用户根据一些随机问题进行测试。我的 models.py 有这两个类:

class Question(models.Model):
content = models.CharField()
...

class Answer(models.Model):
content = models.CharField()
isCorrect = models.BooleanField()
question = models.ForeignKey(Question)

在我的views.py 中,我使用此查询得到 20 个随机问题:

questions = Question.objects.order_by('?')[:20]

通过这种方法,我只有问题,但我还想要与每个问题相关的答案,我找到了一些解决方案,但我想知道获得问题和相关答案的最佳实践是什么?我可以将它们添加到问题构造函数中吗?

谢谢!

最佳答案

您可以按照@karthikr所说的那样操作,但它会为每个问题进行额外的数据库调用。

我可能会这样做:

questions = Question.objects.order_by('?')[:20]
answers = Answer.objects.filter(question__in=questions)

#some databases will not suppoert this, so use:
#answers = Answer.objects.filter(question_id__in=[q.id for q in questions])

for question in question:
answers_for_question = filter(lambda answer:answer.question_id = question_id, answers)

这只是 2 次 db 调用,而不是 21 次

(对于大量问题,请使用 itertools 来获取答案。以获得更好的性能)

关于python - Django - 连接两个模型的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18276473/

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