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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…