我试图在Django中创建两个模型,"段落"one_answers"句子"。我似乎仍然不明白多对一函数是如何工作的。如果我希望有一个段落包含多个句子;我只是在句子模型中添加一个ForeignKey(段落(吗?这样,我就可以在Paragraph模型中有多个句子存储。感谢你在我学习Django的过程中提供的任何见解。
class Sentence(models.Model):
text = models.TextField(blank=True)
order_number = models.IntegerField()
def __str__(self):
return self.text
class Paragraph(models.Model):
text = models.TextField(blank=True)
order_number = models.IntegerField()
sentences = models.ForeignKey(Sentence, on_delete=models.CASCADE)
def __str__(self):
return self.text
ForeignKey
是多对一关系。这意味着定义模型的多个项可以链接到目标模型的同一项。
因此,CCD_;"父";模型和CCD_;"孩子";型号:
class Paragraph(models.Model):
text = models.TextField(blank=True)
order_number = models.IntegerField()
def __str__(self):
return self.text
class Sentence(models.Model):
text = models.TextField(blank=True)
order_number = models.IntegerField()
paragraph= models.ForeignKey(
Paragraph,
on_delete=models.CASCADE,
related_name='sentences'
)
def __str__(self):
return self.text
因此,你可以制作一个Paragraph
和多个句子,这些句子都链接到同一段落:
p1 = Paragraph.objects.create(text='Act 3, Scene 1', order_number=0)
s1 = Sentence.objects.create(
text='To be, or not to be, that is the question',
paragraph=p1,
order_number=0
)
s2 = Sentence.objects.create(
text='Whether 'tis nobler in the mind to suffer',
paragraph=p1,
order_number=1
)
然后,您可以使用查询p1
的所有相关语句
p1.sentences.all()