user9931820
user9931820

Reputation:

One-To-Many Relationship Django

I am coding up a dictionary using Django. I want a word to have multiple definitions, if necessary. This would be a one-to-many relationship, but Django does not seem to have a OneToManyField.

This is a snippet of my code:

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")

I would like to do word.definitions and get back all the definitions of that word. Also, deleting a word should delete all definitions of that word. Finally, a_definition.word should give me the word associated with that definition.

Upvotes: 6

Views: 8766

Answers (1)

Matej
Matej

Reputation: 820

You have to use ForeignKey in Definition class. Definition will have relation to 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)

And you can query it likes this:

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))

Upvotes: 7

Related Questions