【1】模型如下
from django.db import models
class Question(models.Model):
'''
投票问题类
'''
question_text = models.CharField('问题文本',max_length=200)
pub_date = models.DateTimeField('发布日期')
def __str__(self):
return self.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):
return self.choice_text
【2】django 默认每个主表的对象都有一个“外键属性”,可以通过“外键属性”来查询到所有属于主表的子表的信息。这个属性的名称默认是以 子表的名称(小写)加上 _set() 来表示,默认返回的是一个 querydict 对象。
于是,就可以用 question.choice_set.all 获取 Question类的具体对象 question 的全部关联信息。在视图文件中,使用示例如下:
<h2> {{ question.question_text }} </h2>
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
{{ choice.choice_text }}<br />
{% endfor %}
</form>