Models referring to each other - how can I most efficiently fix this issue?
<p>I have a Django application that contains two models - <code>Company</code> and <code>User</code>. These are each in separate files. Each <code>User</code> has a <code>Company</code> by a <code>model.ForeignKey</code> field:</p>

<p>company.py:</p>

<pre><code>class Company(models.Model):
    name = models.CharField(max_length=32)
    is_admin = models.BooleanField(default=False)
</code></pre>

<p>user.py:</p>

<pre><code># 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)
</code></pre>

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

<pre><code>    def list_admins(self):
        return User.object.filter(is_admin=True);
</code></pre>

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

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

<pre><code>def list_admins(self):
    return User.object.filter(company__is_admin=True);
</code></pre>

python django django-models