I'm building a large Django application and would like to split my data models up in a 'class-per-file' structure, but in attempting to do so I'm running into circular dependency issues on some of the more complex models.
For example, I have three models, all in separate files:
class Book(models.Model):
title = models.CharField(max_length=35)
author = models.ForeignKey(Author)
genre = models.ForeignKey(Genre)
class Genre(models.Model):
name = models.CharField(max_length=20)
sample_book = models.ForeignKey(Book)
class Author(models.Model):
name = models.CharField(max_length=60)
preferred_genre = models.ForeignKey(Genre)
Since Book depends on Genre and Genre depends on book, when I import Book anywhere, it would start a chain of circular model dependencies since each file imports the model from the other files. How can I avoid this? This is the kind of project that will grow very large very quickly so I don't want to just lump all of the models into one file.
You can also specify the model name as a string:
preferred_genre = models.ForeignKey("Genre")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With