Context
In the process of data modeling, I use Django models. The main model is Article . It contains actual content.
Then each Article should be attached to a group of articles. This group can be Blog , a Category a Portfolio or Story . Each Article should be attached to one and exactly one of them. That is, it is a blog, category or story. These models have very different fields and functions.
I thought of three ways to achieve this goal (and a bonus that really looks wrong).
Option # 1: Shared Foreign Key
As in django.contrib.contenttypes.fields.GenericForeignKey . It will look like this:
class Category(Model):
On the database side, this means that there is no relationship between the models; they are executed by Django.
Option # 2: Multipage Inheritance
Make article groups all inherited from the ArticleGroup model. It will look like this:
class ArticleGroup(Model): group_type = ForeignKey(ContentType) class Category(ArticleGroup):
On the database side, this creates an additional table for ArticleGroup , then Category and Blog have an implicit foreign key to this table as the primary key.
Sidenote: I know that there is a package that automates the accounting of such designs.
Option # 3: Manual OneToOneFields
On the database side, this is equivalent to option # 2. But in the code, all relationships become explicit:
class ArticleGroup(Model): group_type = ForeignKey(ContentType) class Category(Model): id = OneToOneField(ArticleGroup, primary_key=True)
I really don't understand what is the point of this, besides the fact that an explicit indication of what Django inheritance magic inherits from is implicitly doing.
Bonus: multi-column
This seems pretty dirty, so I just add it as a bonus, but you can also define a NULL key value for each of the Category , Blog , ... directly in the Article model.
So...
... I can not decide between them. What are the pros and cons of each approach? Is there a best practice? Did I miss the best approach?
If that matters, I am using Django 1.8.