【问题标题】:Django unique_together from abstract model field来自抽象模型字段的 Django unique_together
【发布时间】:2018-12-28 16:10:54
【问题描述】:

假设我有一个抽象模型:

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_together 将 some_field 限制为 _active 字段,我拥有的软删除功能使用了该字段。

这行得通,但是,我有一个唯一约束的每个模型现在都需要将_active 应用于唯一性,因为删除时它并没有真正删除,只有_active = None

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

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

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

【问题讨论】:

    标签: python django python-3.x django-models


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 2011-08-05
      • 1970-01-01
      • 2016-01-12
      • 2015-08-01
      • 2018-02-13
      • 1970-01-01
      • 2021-03-27
      • 2013-05-06
      相关资源
      最近更新 更多