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 
<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.charlo...@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
> 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.
> 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
> 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/A001F887-DF85-4B6D-AA85-FB298A2AC9CA%40gmail.com.

Reply via email to