[Answered ]-Django creating a new model for genre or include it in book model?

1๐Ÿ‘

โœ…

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)

Leave a comment