我正在使用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
类中使用ForeignKey
。Definition
将与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))