首页 > 解决方案 > 如何将 ExclusionConstraint 与可能已经删除无效记录的 inline_formset 一起使用?

问题描述

django.contrib.postgres.field.DateRangeField在具有排除约束的模型中使用以确保 2 个日期范围不重叠:

class MyModel(models.Model):
    date_range = DateRangeField()

    class Meta:
        constraints = [
        ExclusionConstraint(
            name='exclude_overlapping_periods',
            expressions=[
                ('date_range', RangeOperators.OVERLAPS),
            ],
        ),
    ]

这行得通,但失败了integrityError(因为它应该)。

我想用一种干净的方法验证模型以做出用户友好的响应:

    def clean(self):
        error_dict = {}

        if MyModel.objects.exclude(id=self.id).filter(
            date_range__overlap=self.date_range):

            error_dict['date_range'] = ValidationError(
            'Range can not overlap with an existing period.',
            code='overlap_period')

        if error_dict:
        raise ValidationError(error_dict)

这有效,但在我使用 ainline_formset并且一个实例被删除的同时另一个实例被更新时不起作用。

我想允许 inline_formset 删除一些记录并更新其他记录(可能与先前删除的记录重叠),但仍保持对所有未删除记录的排除。

问题似乎是clean并且validate_unique在保存模型之前(显然)被调用。这意味着在验证之前不会删除已删除的记录,因此总是会抛出错误。

我怎么能适应这个?

标签: djangodjango-models

解决方案


推荐阅读