这里有两个重要的问题:第一:如何创建choice_set
。 第二:它是什么?
对于像我这样的新开发人员,让我描述一下我如何简化它。首先回答第二个问题。“它是什么”,通过这三个词?模型实例、与该实例相关的对象集、关联管理器。
Django教程中的models.py:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
实例:
q = Question.objects.get(pk=3)
# Here q is an instance of model class 'Question'.
c = Choice.objects.get(pk=32)
# Here c is an instance of model class 'Choice'.
'Model Instance' is a single 'ROW' of an entire 'TABLE' of your database
在这里,
Question Model
作为
Choice Model
的
foreign key
被使用。因此,可以通过以下方式筛选与实例 q 相关的所有
对象集合:
q.choice_set.all()
因此,这里的
choice_set
是与pk=3的问题相关的所有选项。
现在,第一个问题的答案需要第三个单词
Related Manager。Django文档
在这里中解释道:如果一个模型有一个ForeignKey,那么外键模型的实例将可以访问返回第一个模型的所有实例的Manager。默认情况下,这个Manager的名称为FOO_set,其中FOO是源模型名称的小写形式。这个Manager返回QuerySets,可以像上面的“检索对象”部分所述的那样进行过滤和操作。
可以使用Foreign_key中的“related_name”参数来更改这个词(choice_set)。
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="choices")
对于通过外键进行的反向关系:
q.choice_set.all()
q.choices.all()
前向关系:
choice_qs = Choice.objects.all()
choice_qs.filter(question=q)