一对多关系 Django

One-To-Many Relationship Django

我正在使用 Django 编写字典。 如有必要,我希望一个词有多个定义。 这将是一对多的关系,但 Django 似乎没有 OneToManyField.

这是我的代码片段:

class Definition(models.Model):
    definition = models.CharField(max_length=64)

class Word(models.Model):
    word = models.CharField(max_length=64, unique=True)
    definitions = models.ForeignKey(Definition, on_delete=models.CASCADE, related_name="word")

我想 word.definitions 并取回该词的所有定义。 此外,删除一个词应该删除该词的所有定义。最后,a_definition.word 应该给我与该定义相关的词。

您必须在 Definition class 中使用 ForeignKeyDefinition 将与 Word 相关:

from django.db import models

class Definition(models.Model):
    definition = models.CharField(max_length=64)
    word = models.ForeignKey(Word, on_delete=models.CASCADE)

class Word(models.Model):
    word = models.CharField(max_length=64, unique=True)

你可以这样查询:

from .models import Word, Definition

word = Word.objects.get(word = 'test')   #get Word object
definitions = Definition.objects.filter(word = word)   #get all Definition objects related to word object above

for definition in definitions:   #print all definitions related to word
    print('%s -> %s' % (word.word, definition.definition))