Reputation: 2634
I've got some models:
class Place(models.Model):
name = models.CharField(unique=True)
class Bar(Place):
drinks = models.ManyToManyField('Drink')
class Restaurant(Place):
meals = models.ManyToManyField('Meals')
That's a multi-table inherited structure where each bar serves drinks only, and each restaurant serves meals only. I, though, need a name of each place to be unique across all the places - hence the parent Place
model.
Now, multi-table inheritance presumes a parent and a child are separate entities. That means when I want to create a new Bar
, I should go like this:
>> parent = Place(name='Myplace')
>> parent.save()
>> child = Bar(place=parent, drinks=mydrinklist)
>> child.save()
But in my case, Place
is not a separate entity: it should not exists by itself. It's just a shared storage with some restrictions. I'd like to have something like this:
>> child = Bar(name='Myplace', drinks=mydrinklist)
>> child.save()
Where name
attribute is automatically passed to the underlying parent model and a Place
model is silently created when save()
is called. SQLAlchemy can do that via its multi-table inheritance. Is there a way to achieve the same in Django?
Upvotes: 2
Views: 3830
Reputation: 48485
Django's abstract base classes solve the problem of sharing common fields between models:
class Place(models.Model):
name = models.CharField(unique=True)
class Meta:
abstract = True
Edit: Having said that, as Daniel mentioned in the comments, the solution you propose should work just fine. Here's more on Django's multi-table inheritance
Upvotes: 8