Django model 外键的反向引用

class Question(models.Model):
question_text=models.CharField(max_length=200)
pub_date=models.DateTimeField('datepublished')

def__str__(self):
returnself.question_text

class Choice(models.Model):
question=models.ForeignKey(Question,on_delete=models.CASCADE)
choice_text=models.CharField(max_length=200)
votes=models.IntegerField(default=0)

def__str__(self):
returnself.choice_text


上例中,Choice 引用了 Question 作为外键,在模板中通过 Question 对象获取所有引用了 Question 对象的 Choice 对象,可以使用以下方法:

{% for choice in question.choice_set.all %}
<li>{{choice.choice_text}}</li>
{%endfor%}

使用 question.choice_set.all 的方式获取所有引用 question 对象的 Choice 对象实例