One-To-Many Relationship Django
Asked Answered
L

1

6

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.

Lupita answered 11/3, 2020 at 17:8 Comment(0)
M
7

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))
Meatball answered 11/3, 2020 at 17:19 Comment(2)
Is there any use for a related_name field option for cases like this?Lupita
@FredPercudani I found this answer on reddit, which seems useful: reddit.com/r/django/comments/76a7uw/related_name_in_modelspy As I understand, you can call word.definition_set.all() to get all definitions by given word object but I don't see big advange in changing related_name to something different.Meatball

© 2022 - 2024 — McMap. All rights reserved.