Reputation: 2685
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
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
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:
Here's some additional information to be aware of: https://github.com/kdeldycke/awesome-falsehood#postal-addresses
Upvotes: 1