首页 > 解决方案 > 来自抽象模型字段的 Django unique_together

问题描述

假设我有一个抽象模型:

class SoftDelete(models.Model):
    _active = models.NullBooleanField(default=True)

class Meta:
    abstract = True

以及从这个抽象模型中继承的模型:

class SomeModel(AbstractModel):
    some_field = models.IntegerField()

class Meta:
    unique_together = ('_active', 'some_field')

在这里,我通过使用 unique_togethersome_field对字段进行了约束,我拥有的软删除功能使用了该字段。_active

这很有效,但是,我有一个唯一约束的每个模型现在都需要应用_active到唯一性中,因为删除时它并没有真正被删除,只有_active = None.

我的问题是,由于我的所有模型都将失效,SoftDelete是否有一种有效的方法可以应用于_active所有在其 Metas 中具有 unique_together 约束的模型?而不是手动添加它,也许会忘记它。

我希望在抽象的 Meta 类中添加如下内容:

For unique_together in child_unique_together:
    unique_together.append('_active')

标签: pythondjangopython-3.xdjango-models

解决方案


回答我自己的问题:由于找不到更好的解决方案,我使用了艰难的方法并逐个模型地实现了独特的共同模型。


推荐阅读