Django中的一对多关系

6
我正在使用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应该给出与该定义相关联的单词。
1个回答

7

您需要在 Definition 类中使用 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))

像这种情况下,related_name字段选项有何用处? - user9931820
1
@FredPercudani 我在 Reddit 上找到了这个看起来很有用的答案:https://www.reddit.com/r/django/comments/76a7uw/related_name_in_modelspy/ 据我所知,您可以调用word.definition_set.all()来获取给定单词对象的所有定义,但我没有看到将related_name更改为其他内容的巨大优势。 - Matej

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接