django - 从子模型覆盖父模型属性

标签 django django-models

我有以下模型父

class ModelParent(PolymorphicModel):

    company = models.CharField(max_length=50)
    .......

和模范 child
class ModelChild(ModelParent)

     company = models.CharField(max_length=10, blank=True)
     ...........

我怎样才能让模型 child 公司属性覆盖父级 公司没有制作 的模型属性摘要父模型

最佳答案

这是 not possible不幸的是,没有抽象的父模型。

Field name “hiding” is not permitted

In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this isn’t usually permitted for model fields. If a non-abstract model base class has a field called author, you can’t create another model field or define an attribute called author in any class that inherits from that base class.

This restriction doesn’t apply to model fields inherited from an abstract model. Such fields may be overridden with another field or value, or be removed by setting field_name = None.



建议改为简单地创建一个属性或重命名子模型的字段。您可以做的另一件事是删除父模型的“公司”字段并将其移动到所有子模型。
class ModelChild(ModelParent)

 child_company = models.CharField(max_length=10, blank=True)
 ...........

关于django - 从子模型覆盖父模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51772164/

相关文章:

Django celery 任务重复 : can't lock DB?

django - django事务大小的自适应优化

python - “heroku run python manage.py migrate”失败并出现错误 'Error R13 (Attach error) -> Failed to attach to process'

Django:反向 OneToOneField 匹配,无需 related_name

python - Django 1.7b4中继承BaseUser错误

python - 具有多个数据库的 Django,来自管理员中非默认数据库权限的模型

django - 如何在 Django 中使用 s3 到 base64 在 FileField 中编码文件?

python - 在 django 中不使用交互式 python shell 将值插入数据库表

django - 在django模型保存方法中获取ManytoMany字段的选定值

python - Django:如何在抽象模型类中设置ForeignKey related_name?