I have a book model and every book has a genre. I'm confused if 1) I should create a new Model for genre then create a many to one relationship between book and model..... or 2) should I just include genre as a field in the Book model?
If I wanted to get all books for a specific genre would using 1) make the search faster/more efficient since I could get all the books associated with a genre object? Because If I use 2) I would have to filter through every book to see if it has the specified genre.
CodePudding user response:
If you repeat the same value multiple times, that is a form of data duplication. Often data duplication is a problem: imagine that you spot a typo in the name of the genre
, then you will need to update all records, which is expensive. If you later want to add extra data to the genre, like a description, that should be done on all book records, resulting in a large database, and finally it also means that you only can create a genre if you have at least one book with this genre. This are all reasons why this is not a good idea.
You thus usually create a Genre
model, and then work with a ForeignKey
from Book
to Genre
, like:
from django.db import models
class Genre(models.Model):
name = models.CharField(max_length=32, unique=True)
def __str__(self):
return self.name
class Book(models.Model):
# …
genre = models.ForeignKey(Genre, on_delete=models.CASCADE)