[Fixed]-What are the pros and cons of using GenericForeignKey vs multitable inheritance vs OneToOneField?

11πŸ‘

βœ…

It seems noone had advice to share on that one.
I eventually chose the multicolumn option, despite having said it looked ugly. It all came down to 3 things:

  • Database-based enforceability.
  • The way Django ORM works with the different constructs.
  • My own needs (namely, collection queries on the group to get the item list, and individual queries on the items to get the group).

Option #1

  • Cannot be enforced at the database level.
  • Could be efficient on queries because the way it is constructed does not fall into usual generic foreign key pitfalls. Those happen when the items are generic, not the collections.
  • However, due to how the ORM handles GFK, it is impossible to use a custom manager, which I need because my articles are translated using django-hvad.

Option #2

  • Can be enforced at the database level.
  • Could be somewhat efficient, but runs into ORM limitations, which is clearly not built around this use. Unless I use extra() or custom queries alot, but at some point there is no reason to use an ORM anymore.

Option #3

  • Would actually be a bit better than #2, as making things explicit allows easier query optimisation while using the ORM.

Multicolumn

  • Turns out not being so bad. It can be enforced at the database level (FK constraints plus a manual CHECK to ensure only one of the columns is non-null).
  • Easy and efficient. A single intuitive query does the job: select_related('category', 'blog', ...).
  • Though it does have the issue of being harder to extend (any new type will require altering the Articleβ€˜s table as well) and limiting the possible number of types, I’m unlikely to run into those.

Hope it helps anyone with the same dilemma, and still interested in hearing other opinions.

πŸ‘€spectras

Leave a comment