我使用 django-reversion 来控制模型的更改,但模型清理方法有问题。
例如我的模型如下所示:
class Document(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
client = models.ForeignKey(Client, on_delete=models.CASCADE)
template = models.ForeignKey(Template, on_delete=models.CASCADE)
def clean(self):
if self.template.only_one and (Document.objects.filter(client=self.client, template=self.template).count() > 0):
raise ValidationError('Test')
我在 admin.py 中注册这个模型:
@admin.register(Document)
class DocumentReversion(VersionAdmin):
pass
现在,我在管理部分中为文档创建一条记录,引用字段 only_one
为 True
的模板。
如果我删除该记录并检索它,则会触发 ValidationError 。
为什么?因为我已经删除了唯一可用的记录。很好奇...
最佳答案
任何更新都会执行清理。如果您编辑您的文档
,那么它也会检查给定的条件。由于该条件成立:模板具有 only_one=True
,并且存在这样的文档(您的文档),因此它将引发 ValidationError
。
因此,您需要从查询集中排除当前项目:
class Document(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
client = models.ForeignKey(Client, on_delete=models.CASCADE)
template = models.ForeignKey(Template, on_delete=models.CASCADE)
def clean(self):
qs = Document.objects.filter(client_id=self.client_id, template_id=self.template_id)
if <b>self.pk is not None</b>:
<b>qs = qs.exclude(pk=self.pk)</b>
if self.template.only_one and qs.exists():
raise ValidationError('A document with this template already exists')
return super().clean()
如果这样设置主键,我们可以从查询集中排除该主键。事实上,我们在这里不需要 if 条件,因为 .exclude(pk=None)
无论如何都会成功。
关于python - django-reversion 与模型 clean 方法冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154230/