django - 如何将 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
在保存模型之前(显然)被调用。这意味着在验证之前不会删除已删除的记录,因此总是会抛出错误。
我怎么能适应这个?
解决方案
推荐阅读
- python - 将值写入空的字典列表
- python - Python 从 SQLite3 DB 返回意外的值
- c - 我如何用这段代码破坏内存?
- swift - 为什么路径会朝着相反的方向绘制?
- c++ - 列表迭代器参考 - 程序输出
- sql - 在 Oracle DBMS 中的多个列上使用过滤条件连接表
- python - TypeError: 不支持的操作数类型 -: 'NoneType' 和 'int'
- python - 尝试从应用程序导入模型会引发 ImproperlyConfigured 异常
- jenkins - 在詹金斯中实现长时间运行的作业的惯用方法是什么?
- javascript - useEffect 中的 js 承诺链是否保证在被垃圾收集之前完成?