Blog (or) Scribble Pad

Django: using a Model from an app as a Foriegn Key to another app's model

Rich is a model in an app named strain. I have another app in the same Django project called grain which has a model named Poor. I now want to use the model Rich as a foreign key to the Poor model.


We shouldn't import the model directly as it will lead to circular import dependency.

A short note on circular import dependency:
Lets assume that we have two modules in a same directory each importing each other.

module 1 -> a.py

from b import dexter
# rest of the file

module 2 -> b.py

import a

def dexter():
    #dexter function

# rest of the file
If we try to run the b.py module then it will try to import the module a. During the process of import, the a.py will try to import dexter from b.py which in this situation wasn't defined yet as we are still executing the first line of b.py. So no dexter function will be found to import leading to an error.

Lazy Relationship is what we wanted!
We shouldn't explicitly import the model to avoid circular import problems.

grain>models.py file

class Poor(models.model):
    rich = models.ForeignKey('grain.Rich')
    # remaining of the class

This simply solves our problem.

If we already have a Poor and Rich models with data in them we should take care of them first before migrating our database to new changes.