Django:将公共字段存储在父模型中 [英] Django: store common fields in a parent model

查看:82
本文介绍了Django:将公共字段存储在父模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些型号:

class Place(models.Model):
    name = models.CharField(unique=True)

class Bar(Place):
    drinks = models.ManyToManyField('Drink')

class Restaurant(Place):
    meals = models.ManyToManyField('Meals')

这是一个多表继承的结构,其中每个酒吧仅提供饮料,而每个餐厅仅提供餐点.但是,我需要每个位置的名称在所有位置上都是唯一的-因此,父级Place模型.

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.

现在,多表继承假定父级和子级是单独的实体.这意味着当我想创建一个新的Bar时,我应该这样:

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()

但是在我的情况下,Place不是一个单独的实体:它不应该单独存在.它只是一个共享存储,但有一些限制.我想要这样的东西:

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()

name属性将自动传递给基础父模型,并且在调用save()时以静默方式创建Place模型. SQLAlchemy可以通过其多表继承来做到这一点.有没有办法在Django中实现相同的目标?

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?

推荐答案

Django的抽象基类解决了在模型之间共享公共字段的问题:

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

编辑:就像Daniel在评论中提到的那样,您建议的解决方案应该可以正常工作.有关 Django的多表继承的更多信息,

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

这篇关于Django:将公共字段存储在父模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆