views:

26

answers:

2

Here are my schematic models:

class Law(models.Model):
    ... 

class Bill(models.Model):
    ... # data for a proposed law, or change of an existing law

class PrivateBill(Bill):
    ... # data for a Bill that was initiated by a parliament member

class GovernmentBill(Bill):
    ... # data for a Bill that was initiated by the government

It is possible and likely that in the future I (or maybe someone else) would want to add more Bill types.

Every Bill should point to a Law (indicating what law this bill is going to change) and my question is: What is the best way to implement this?

If I add the ForeignKey(Law) to Bill, I'll have a relation from every Bill to Law, but a Law would only have an inverse relation to Bills (bill_set), and not a different inverse relation to each type of bill. Of course I'll be able to filter each type of bill to get only the ones pointing to a specific Law, but this is something I think I'll need to use often, so I think having privatebill_set, governmentbill_set etc would make the code more readable.

Another possible solution is to add the foreign key to each of the inheriting classes (this would give me a privatebill_set, governmentbill_set, futurebill_set), but that seems hairy because I would be relying on future programmers to remember to add that relation.

How would you solve this?

+2  A: 

Maybe you can make your Bill class abstract and do it like this:

class Bill(models.Model):
    law = models.ForeignKey(Law, related_name="%(app_label)s_%(class)s_related")

    class Meta:
        abstract = True

class PrivateBill(Bill):
    pass

class GovernmentBill(Bill):
    pass
aeby
Great idea. Thanks.
Ofri Raviv
A: 

Generic relations might be the way to go here - they allow you to have a structure similar to a ForeignKey which points at any other model.

Daniel Roseman