Chris vCB Chris vCB - 2 months ago 7
Python Question

Models referring to each other - how can I most efficiently fix this issue?

I have a Django application that contains two models -

Company
and
User
. These are each in separate files. Each
User
has a
Company
by a
model.ForeignKey
field:

company.py:

class Company(models.Model):
name = models.CharField(max_length=32)
is_admin = models.BooleanField(default=False)


user.py:

# Ignore the clumsy in this import for a moment
from package.models.company import Company

class User(models.Model):
name = models.CharField(max_length=32)
company = models.ForeignKey(Company)


Now, one thing I want to do is to add a method
list_admins
to
Company
(not
User
), whereby it would give me a list of all users who happen to have
is_admin
set to
True
:

def list_admins(self):
return User.object.filter(is_admin=True);


But of course that would require me to import
User
in Company, which I can't, as I can't import
User
in
Company
and
Company
in
User
at the same time owing to its circularity.

So how does one resolve this in a Pythonic/Djangoic way?

Answer

You can use the reverse ForeignKey relation on each Company to access their respective Users:

def list_admins(self):
    return self.user_set.filter(is_admin=True)

Doc. reference: Following relationships “backward”