Django: store common fields in a parent model

梦想与她 提交于 2020-01-05 14:07:34

问题


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?


回答1:


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




回答2:


As Daniel Roseman mentioned, I was totally wrong: Django does actually work that way I described.



来源:https://stackoverflow.com/questions/21304025/django-store-common-fields-in-a-parent-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!