[Answered ]-Django makemigrations error when there are 3 custom model in a models.py

2๐Ÿ‘

โœ…

Iโ€™ll explain the error with an example:

Supose you have these two models.

class Book(Models.model):
    title = models.CharField(maxlength = 100)

class Person(Models.model):
    name = models.CharField(max_length = 100)
    own_book = models.ForeignKey('Book')

Simple models, but the tricky part is that Django builds reverse references whenever you define a foreign key: If person is a query object, foward reference to the title of the book she owns would be: person.own_book.title.

Now, if you want to know persons names that own a particular book? Django builds the reverse relationship, which takes the model name by default. That is, โ€˜bookโ€™ being a queryset object, you can find the names of persons that owns the book with book.person.name. Cool, right? It looks through your foreign key.

Now, add another foreign key to the same book model:

class Person(Models.model):
    name = models.CharField(max_length = 100)
    wrote_book = models.ForeignKey('Book')
    own_book = models.ForeignKey('Book')

Your foward relationships are still well defined: person.wrote_book.title and person.own_book.title. But what book.person.name is suposed to do? Look for names of persons that owns the book? that have written the book? or both? There django just throws your Reverse acessor error.

How to fix it? Djangos tells you to create a related_name in your model:

class Person(Models.model):
    name = models.CharField(max_length = 100)
    wrote_book = models.ForeignKey('Book', related_name = 'wrote')
    own_book = models.ForeignKey('Book', related_name = 'own')

So book.person.name does not exists anymore (default is overwritten) and it is replaced by book.own.name and book.wrote.name.

So my guess is: look for foreign keys defined in groups and user_permissions models and put related_names parameters on them.

๐Ÿ‘คAlex

Leave a comment