I have an API (built with DRF + Django 3.1) and I need to share a model (Address Table) across multiple other models (Users, and Places). So for example, I want to share the Address table for Users and Place (maybe this is a database limited I have to live with, but I just don’t know if this is possible so some guidance is much appreciated).
I have already looked into GenericForeignKey and ContentType to achieve this, however, I find it to be brtittle.
What do you mean by “share the Address table for Users and Place”?
In the typical case, you would have a ForeignKey in Users referring to Address, and a ForeignKey in Place referring to Address. (Each address identifies a unique location, which can be occupied by multiple people or even “Places” depending upon what you mean by a “Place”. This means that the Address is on the “One” side of a One-to-many relationship.)
Thanks for your response @KenWhitesell. I think you caught on right at the end there and answered my question. This brings me to my follow up concern. If I follow this route, then it means each User and Place (a place in this context is an entity with an address; a house, an office, a restaurant, etc) can only have on address. I was think that a user should be able to create multiple addresses.
That’s fine. If that’s the case, then this expands the User - Address relationship to become a Many-to-Many. (Each Address can be related to many Users, Each User can be related to many Addresses.)
This sounds like exactly the scenario for a many-to-many foreign key table:
One of the neat features of Django is that is builds this “through” table for you automatically. Then you only need to define three models: User, Address, and Place. The relationship tables (user_addresses, place_addresses) are built for you automatically when you define a m2m foreign key in the User and Place models.
That being said, what exactly is a Place representing in your schema? Typically, I would imagine that Address would be a field of Place, rather than a separate model. Why does a Place need multiple Addresses?
Thanks for your response @dstarkebaum. Place in my schema is representing a physical “place” that has an address (maybe a restaurant which would also have a name). To answer your last question, I removed the need for a Place to have multiple addresses, only a User should be able to have multiple addresses.
But I have been thinking, should I denormalize the Place table and allow it to have its own address fields (i.e., no relationship with the Address table)?
To me, Place seems a bit too generic, and it’s hard for me to see what other information it might include that is not part of Address. Perhaps it’s better to add a more specific “Business” table instead? It also depends a bit on the purpose of your database (Ex: OLTP vs OLAP):