Search code examples
pythondjangomodels

django models dependancy between two classes


I have 2 models in my django app, where both the models contain multiple instances of the other class. Eg) Say a topic can contain many books, and a book may belong to many topics. So, both must have a manytomanyfield of the other. My code:

class Topic(models.Model):
    books = models.ManyToManyField(Book)

class Book(models.Model):
    topics = models.ManyToManyField(Topic)

Now the problem is, i get an error as 'Book' is not defined. How do I get rid of this?


Solution

  • Pass the name of the model as a string to ManyToManyField instead of the model itself, see here (ForeignKey behaves the same way).

    Code:

    class Topic(models.Model):
        books = models.ManyToManyField('Book')
    
    class Book(models.Model):
        topics = models.ManyToManyField('Topic')
    

    Edit:

    I blindly answered this without noticing the same thing as Daniel. You only need to have this relationship defined in one of the models, not both ways.