Django error CircularDependencyError



  • Two models.

    Prices/models.py

    import Books.models import Books
    

    class Prices(models.Model):
    book_id = models.ForeginKey(Books, on_delete=models.DO_NOTHING)
    # ... other fields

    Book files/models.py

    import Prices.models as pr_model

    class Books(models.Models):
    price_id = models.ForeignKey('Prices.Prices', on_delete=models.DO_NOTHING)
    # ... other field

    def save(self, *args, **kwargs):
        price = pr_model.Prices.objects.all()
        # ... some logic and saving price object or create
    

    With this import of packages, I get a mistake that makes sense.

    django.db.migrations.exceptions.CircularDependencyError:
    Books.0001_initial, Prices.0001_initial

    In the case of the initial migration of both django applications, the error mentioned above will be made. However, if imported in the Books and then rewrite and migrate data again, there will be no error.

    Tell me, can this cause problems in the future? Maybe there's a better way to make these manipulations and not break the import of bags?



  • If the jango says cycling isn't good, it's not good. Your book-id model refers to the Books model, in your case, the best solution will be to add related_name to the book_id model, and in Book/models.py, even remove the import Price/models.py.

    You can do this:

    import Books.models import Books
    

    class Prices(models.Model):
    book_id = models.ForeginKey(Books, related_name'related_book' on_delete=models.DO_NOTHING)

    In the future, you may interact with the models involved in such a way as:

    Price.book_id will store a books model, and a books model can be used: books.related_book.all() - It'll bring back all models that will refer to a specific model.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2