How to Model a relationship on a constrained subset of the foreign key.
HI. I have a newbie-ish question, if that's alright. I don't know how to
model a particular relationship in Django.
I have an Account model which represents a customer account - billing
address, balance and all that. And I have a Contact model, which
represents actual people we would pick up the phone and call. The
relationship of Contact to Account is Many to One and I have set a
ForeignKey(Account) attribute on the Contact model. This is all fine so far.
Accounts can have a variable number of divisions within them, e.g.
Europe, America, whatever. I have therefore created a Division model
which has a ForeignKey(Account) attribute as well. This is fine -
divisions are attached to accounts, they don't cross account boundaries
even if two Accounts had a "Europe" division for example, they're not
actually the same division.
I want to have contacts optionally assigned to a division as well as to
an account. I can do that by giving the Contact model a
ForeignKey(Division) attribute and this works, but I can't find a way of
constraining it to only those divisions that belong to the same Account.
I can fudge it in the forms and views, of course, but it seems there
should be a way of representing this relationship in the models. Do I
create a special Contact-Division model and have foreign keys to it? Is
there a way of doing ForeignKey(Account,Division). How can I do this or
is it not possible to represent this constraint at the model layer? Any
help is much valued.
Thanks,
Taliesin.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home