class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
- 知识点1:Question与Choice的对应关系为一个Question对应多个Choice,因此Choice中的field "question"为ForeignKey
- 知识点2:设置完对应关系后,Question中出现choice_set
通过Question.objects.get(id=1).choice_set.create(choice_text="I dont't know", votes=0)
可以设置某个question的一个choice,通过Question.objects.get(id=1).choice_set.all()
可以获得某个question对应的所有choice的集合