Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better: Foreign Keys or Model Inheritance?

I have this use case scenario: there are places which are either playgrounds, restaurants, theatres, pubs. the same place can have playgrounds, restaurants, theatres etc. there are couple of ways of implementing it:

  1. use foreign keys

    class Place(models.Model):
        name = models.CharField(max_length=50)
    
    class PlayGrounds(models.Model)
        field1 = models.CharField(max_length=50)
        place = models.ForeignKey(Place)
    
  2. multitable inheritance

    class Place(models.Model):
        name = models.CharField(max_length=50)
        address = models.CharField(max_length=80)
    
    class Restaurant(Place):
        serves_hot_dogs = models.BooleanField()
        serves_pizza = models.BooleanField()
    
  3. use abstract class

    class Place(models.Model):
        name = models.CharField(max_length=50)
    
    class PlayGrounds(Place)
        field1 = models.CharField(max_length=50)
        place = models.ForeignKey(Place)
        class Meta:
            abstract = True
    
  4. use proxy models

    class Place(models.Model):
        name = models.CharField(max_length=50)
    
    class PlayGrounds(Place)
        field1 = models.CharField(max_length=50)
        place = models.ForeignKey(Place)
        class Meta:
            proxy = True
    

What are the pros and cons of using each approach?

like image 786
whatf Avatar asked Jan 20 '12 04:01

whatf


People also ask

Why we use foreign key in Django models?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.

Can a model have a foreign key to itself?

Self-referencing foreign keys are used to model nested relationships or recursive relationships. They work similar to how One to Many relationships. But as the name suggests, the model references itself.

Can a model have two foreign keys?

Models can have multiple foreign keys. The best design will depend on how you plan on querying the database.


2 Answers

The first one is essentially model inheritance, because that's what Django's implementation of MTI uses (except it's a OneToOneField instead of a ForeignKey, but that's merely a ForeignKey that's unique).

Anytime you have an is-a relationship (i.e., a Restaurant is a Place), you're dealing with inheritance, so using one of Django's model inheritance methodologies is the way to go. Each, however, has its pros and cons:

Abstract Models

Abstract models are useful when you just want to off-load repetitive fields and/or methods. They're best used as mixins, more than true "parents". For example, all of these models will have an address, so creating an abstract Address model and having each inherit from that might be a useful thing. But, a Restaurant is not an Address, per se, so this is not a true parent-child relationship.

MTI (Multiple Table Inheritance)

This is the one that's akin to your first choice above. This is most useful when you need to interact with both the parent and child classes and the children have unique fields of their own (fields, not methods). So a Restaurant might have a cuisine field, but a Place wouldn't need that. However, they both have an address, so Restaurant inherits and builds off of Place.

Proxy Models

Proxy models are like aliases. They cannot have their own fields, they only get the fields of the parent. However, they can have their own methods, so these are useful when you need to differentiate kinds of the same thing. For example, I might create proxy models like StaffUser and NormalUser from User. There's still only one user table, but I can now add unique methods to each, create two different admin views, etc.

For your scenario, proxy models don't make much sense. The children are inherently more complicated than the parent and it wouldn't make sense to store all the fields like cuisine for Restaurant on Place.

You could use an abstract Place model, but then you lose the ability to actually work Place on its own. When you want a foreign key to a generalized "place", you'll have to use generic foreign keys, instead, to be able to choose from among the different place types, and that adds a lot of overhead, if it's not necessary.

Your best bet is using normal inheritance: MTI. You can then create a foreign key to Place and add anything that is a child of Place.

like image 99
Chris Pratt Avatar answered Nov 16 '22 04:11

Chris Pratt


It depends entirely on what sort of behaviour you need.

Do you need to perform the same kinds of operations on places and restaurants or playgrounds? Will you be checking if your services (restaurants etc) are in the same place? Is it meaningful to treat two places with the same address as being different, and their associated services as different?

Without knowing the answers to these sorts of questions, it is impossible to say which is the most appropriate technique, as they are very different techniques, and not in general substitutes for each other.

The use of inheritance should not be dictated by an pre-conceived notion about taxonomy, because it is not there to model taxonomy: it is there to provide function polymorphism (data member inheritance is there primarily to facilitate that).

like image 36
Marcin Avatar answered Nov 16 '22 02:11

Marcin