繁体   English   中英

如何在 inheritance 之后删除抽象 model 的 model 属性的唯一约束?

[英]How to remove unique constraint for a model attribute of an abstract model after inheritance?

我有一个摘要 class 作为:

class AbstractExecutive(models.Model):
    mobile = models.CharField(max_length=10,unique=True,
                              verbose_name='*Mobile')

   #other attributs not required....
    class Meta:
        abstract = True

我正在继承这个 class 以创建不同的实例,如客户端、供应商等。对于 class 实例客户端,我要求删除唯一约束,而其他 class 对象存在该约束。 我正在使用 postgresql 9.1 我使用 psql 删除了客户端表约束,但由于 model 是继承的,它始终具有唯一约束。 请注意,Client 表有数据,不能被打扰。 我怎样才能摆脱表中的约束。 客户 class model:

class Client(AbstractAddress,AbstractExecutive):

    number = models.CharField(max_length=10,verbose_name='number',
                                  unique=True)
    #other attributes...

您可以尝试覆盖Client的继承mobile字段:

class Client(...):
    ...
Client._meta.get_field('mobile')._unique = False

不幸的是,这在django中是不可能的( https://docs.djangoproject.com/en/dev/topics/db/models/#field-name-hiding-is-not-permitted )。 您需要从抽象类中删除mobile并将其放入具体类(有或没有unique )。

也许旧的 Django 版本不可能,但现在的解决方案是重新定义子 class 的属性,没有unique=True约束。

因此,在给定的示例中,在AbstractExecutive摘要 model 中具有唯一的mobile属性,并且在Client model 中不能是unique的:

您的摘要 class:

class AbstractExecutive(models.Model):
    mobile = models.CharField(max_length=10, unique=True,
                              verbose_name='*Mobile')

   #other attributs not required....
    class Meta:
        abstract = True

子非抽象 class:

class Client(AbstractAddress, AbstractExecutive):
    mobile = models.CharField(max_length=10, verbose_name='*Mobile')

    #other attributes...

生成迁移时,将在Client model 中删除unique约束。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM