Search code examples
databasedjangomodelsdesign-decisions

Tough inheritance database/model design decision


I have Users which can be either TypeS, TypeC, or TypeA. I have models for each of these types to store additional information. Now, in the Users table, should I have

  1. 3 nullable foreign-key fields to designate which type they are
  2. 2 fields, 1 with the name of the type and 1 with the foreign key
  3. 1 field designating the type with the foreign key on the other model
  4. no field on the user, and rely on checking the reverse relationship?

I'm using Django if you want to provide a more refined answer.


Solution

  • Django provides Generic relations as part of the contenttypes framework, which allows you to implement something similar to your option #2, just more flexible. You can establish generic relations by adding the following fields to your model:

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    

    This way you can assign one of TypeS, TypeC, or TypeA to each user in question. Also, should you ever have the need to add a TypeX or a TypeY, you're already set and don't need to extend the model.