Django model which could be associated with two parents
<p>I've got a model in Django that I think it needs to be associated with two parents, but I'm trying to figure out how to code it.</p>

<p>The main problem is that we've got <code>Building</code> models that are linked with a <code>Headquarter</code>. Each <code>Headquarter</code> usually have an <code>ElectricSupply</code> that supplies electricity to all the heardquarter's buildings, but also, it's possible that each <code>Building</code> could have its own <code>ElectricSupply</code>.</p>

<p>Furthermore, each <code>ElectricSupply</code> is linked with one or more <code>ElectricBill</code> model which are stored by months.</p>

<p>So, in the end I must be able to get the <code>Headquarter</code> electric consumption, no matter if the supply is from the hearquarter or each building.</p>

<pre><code>class Headquarter(models.Model):
    # ...
    def get_consumption(self):
        # Here I need to know where to look for the supply

class Building(models.Model):
    # ...
    headquarter = models.ForeignKey(Headquarter, related_name='buildings')

class ElectricSupply(models.Model):
    # Here I don't know where to point, Headquarter or Building, or both?

class ElectricBill(models.Model):
    # ...
    supply = models.ForeignKey(ElectricSupply, related_name='bills')
</code></pre>

<p>Hope you can help me. Thanks.</p>

<p>I think that every building should have ElectricSupply, so you should point to Building from ElectricSupply, and then if you want to find Headquarter you can easily get that from Building where you also have foreign key pointed to Headquarted. Also I think that every building should be in relationship with ElectricBill, so you should change your foreign key in ElectricBill to point on Building.</p>

python django design foreign-keys models