Sunday, November 14, 2021

Re: Question regarding organizing models

You can put a string with the name of a class that is yet to be defined in the ForeignKey.  https://docs.djangoproject.com/en/3.2/ref/models/fields/#foreignkey

In this case you would do

    created_by_id = models.ForeignKey("User", on_delete=models.DO_NOTHING)

On Sep 23, 2021, at 1:50 AM, Bhavin Shah <bhavinks.charlotte@gmail.com> wrote:

Hello,

Somewhat new to Django. I am trying to figure out the best way to define/organize models in Django app which have interdependent foreign keys. Simplified example below.


<Screenshot 2021-09-23 131449.png>

The issue I am struggling with is the following
  1. The above example produces an error as User class is defined after Company. Reversing the order would cause the same issue with reference to Company class in User class. What is the best way to handle this scenario ? I tried to set the created_by_id value post the User class declaration, but then the django migrations do not recognize/set the foreign key correctly.
  2. I also tried to split the models into multiple files as the app is expected to have several models with such interdependent foreign keys. However in that scenario, the import are causing an error due to circular references.
Any suggestions/guidance on best way to handle such models would be very much appreciated. Thank you.

Regards,

Bhavin Shah


No comments:

Post a Comment