Colin
Colin

Reputation: 3752

django user relationship

Using django, say I have model classes A and B, representing different types of Companies. Each Company may have multiple Users associated with it. Obviously I'd like to use django's User model, to get the login, etc. goodness. How would I go about doing that? Would I add a UserProfile that has two foreign keys, one to A and one to B (and the one that isn't null points to the company that the User works for)? Or is there another way?

thanks!

Upvotes: 1

Views: 701

Answers (4)

styts
styts

Reputation: 1023

You would need to reference the Company model, and if need be, subclass Company with CompanyA and CompanyB. For simplicity, your Company class could have a type attribute with possible A and B values, then you could avoid subclassing.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798556

If you really must have different fields inside CompanyA and CompanyB then you can have them both derive from a common Company class which your ForeignKey will point to.

Upvotes: 0

Ofri Raviv
Ofri Raviv

Reputation: 24823

Use inheritance: define a superclass for Company, with the common fields, and then inherit that class and add the stuff ClassACompany and ClassBCompany need.

This way the UserProfile can have a foreign key to Company. If you need to get from the company to the specific type of company, you can do that as described in the docs.

Upvotes: 1

Oren Mazor
Oren Mazor

Reputation: 4477

why dont you just have one class for Company? that'll make your system much, much simpler.

you can then have specific fields inside Company that will let you determine whether it's of type A or B (what's the difference anyway?)

Upvotes: 1

Related Questions