[英]Django: How is <classname>_set attribute created in models.Model subclass?
In Django, I can have a model Question and a model Choice: 在Django中,我可以有一个模型Question和一个模型Choice:
class Question(models.Model):
...
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
...
def __str__(self):
return choice_text
I can then do this: 然后,我可以这样做:
>>>q = Question(question_text = 'How are you?', pub_date = timezone.now())
>>>q.choice_set.all()
<QuerySet []>
The q.choice_set
, according to my understanding, accesses the set of Choice
objects in our database which refer to q
by their foreign key. 根据我的理解, q.choice_set
访问我们数据库中的Choice
对象集,这些对象通过q.choice_set
键引用q
。
My question is: How is the choice_set
attribute being created? 我的问题是:如何创建choice_set
属性? I've never seen a attribute name taking the name of another class in lower case letters. 我从未见过属性名称采用小写字母的另一个类的名称。 How is this achieved? 如何实现的?
EDIT: To clarify, I'm asking about how Django sets the name of the variable dynamically, not the variable contents. 编辑:为澄清起见,我问的是Django如何动态设置变量名称,而不是变量内容。
The name is decided by ForeignObjectRel.get_accessor_name
. 名称由ForeignObjectRel.get_accessor_name
决定。 The actual attribute is set via setattr()
in RelatedField.contribute_to_related_class
. 实际属性是通过RelatedField.contribute_to_related_class
setattr()
RelatedField.contribute_to_related_class
。
Essentially, this happens when you create an instance of ForeignKey
: 本质上,这是在创建ForeignKey
实例时发生的:
attribute_name = YourModel._meta.model_name + '_set'
setattr(foreign_key, attribute_name, SomeDescriptorClass(foreign_key))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.