Django:对象和model_set [英] Django: objects and model_set
问题描述
我正在学习Django 1.10官方教程第2部分
I am learning django 1.10 official tutorial part 2
class Question(models.Model):
# ......
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
#.......
最近我看到了以下命令:-
Recent i saw the following command:-
q = Question.objects.get(id=1)
q.choice_set.all()
我的问题:-
Question实例如何包含 choice_set
,我知道它用于访问相关对象.
How Question instance contain choice_set
, i know it for accessing related objects.
这为什么无效
c = Choice.objects.get(id=1)
c.question_set.all()
推荐答案
Question模型没有对Choice模型的显式引用;但是,Django自动添加反向引用,默认情况下称为choice_set.您可以通过模型上的 related_name 关键字来覆盖它,例如:
The Question model does not have an explicit reference to the Choice model; however, Django automatically adds a reverse-reference, which is by default called choice_set. You can override this by related_name keyword on the model such as:
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices')
现在,您可以参考所有选择来解决这样的问题:
Now you can reference all of the choices for a question like this:
q = Question.objects.get(pk=1)
q.choices.all()
要回答第二个问题,之所以不能使用 choice 对象中的引用 question_set.all()的原因是,对于每个选择,只有一个问题加对该问题对象有一个显式引用.换句话说,选择"模型已经有一个名为"问题"的字段,该字段指向问题"模型.
To answer your second question, the reason you cannot use reference question_set.all() from a choice object is because for each choice, there is only one question plus there is an explicit reference to the question object. In other words the Choice model already has a field called Question, which points to the Question model.
希望有帮助.
这篇关于Django:对象和model_set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!