sebap123
sebap123

Reputation: 2685

Coping with redundant Django models inheritance

I'm trying to figure out how I could cope with following inheritance in Django models.

class Address(models.Model):
     street = models.CharField()
     city = models.CharField()
     country = models.CharField()

     class Meta:
         abstract = True

class Person(Address, models.Model):
     name = models.CharField()

class Caffe(Address, models.Model):
     place_name = models.CharField()
     owner_name = models.CharField()
     signature_drink = models.CharField()

I know I could just inherit after Address and it'll still work. But it doesn't look correct - it makes code and inheritance unclear (assuming each model is in different file). Also, it is redundancy in my opinion to inherit twice from the same class (on different levels, but still). Or maybe it is the only way and it is acceptable by Django standards?

Upvotes: 0

Views: 54

Answers (2)

Muhammad Zeshan Arif
Muhammad Zeshan Arif

Reputation: 475

You don't need to inherit Person and Caffe from models.Model as You are inheriting Person and Caffe from Address and Address is already inheriting from models.Model. Your models structure would be like

class Address(models.Model):
     street = models.CharField()
     city = models.CharField()
     country = models.CharField()

     class Meta:
         abstract = True

class Person(Address):
     name = models.CharField()

class Caffe(Address):
     place_name = models.CharField()
     owner_name = models.CharField()
     signature_drink = models.CharField()

Upvotes: 0

user1600649
user1600649

Reputation:

FYI: there are packages that give you fields that handle addresses.

The reason to use an AddressField or an abstract class with basic fields or the third option, multi-table inheritance depends on your project requirements:

  • Use an encapsulated address model by way of an AddressField to limit the amount of migrations. This AddressField is a subclass of ForeignKey and with some extra functionality to make sure information gets stored correctly. Changes to the address model are only changes to the address model. All addresses are in one place.
  • Use multi-table inheritance when it makes sense that addresses are objects by themselves. The Place and Restaurant is a good example. In addition, you can find a place by searching just the for the place and then see if it's a restaurant or for example a movie theatre.
  • Use abstract models, when you want no shared information between models. Each time you change the abstract model, you create migrations for all models that use it. This can become quite the burden.

Here's some additional information to be aware of: https://github.com/kdeldycke/awesome-falsehood#postal-addresses

Upvotes: 1

Related Questions