Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

python - Django: store common fields in a parent model

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...