我有两个整数列,并且想限制它们在一行中不具有相同的值。例如,
id | type1 | type2 |
------------------------
1 | 1 | 2 |
2 | 1 | 3 |
3 | 3 | 3
第一行和第二行没问题,但第三行应该不存在。 如何在 Django 模型中添加此限制?
最佳答案
在模型中做是丑陋的/不推荐的,你需要这样的东西:
class MyModel(models.Model):
type1 = models.IntegerField()
type2 = models.IntegerField()
def save(self, *args, **kwargs):
if self.type1 != self.type2:
return super().save(*args, **kwargs)
else:
return # cancel the save - which isn't recommended
不建议这样做,因为用户不会得到任何关于出错的反馈,取消保存可能会导致不正确的行为。 (信号、重定向等。可能会失败)
如果可以的话,我建议将 in 作为表单验证。
class MyForm(forms.Form):
type1 = forms.IntegerField()
type2 = forms.IntegerField()
def clean(self):
cleaned_data = super().clean()
if cleaned_data['type1'] == cleaned_data['type2']:
raise forms.ValidationError("Type1 and Type2 need to be different")
编辑 1:修复缩进。
编辑 2:添加表单验证示例。
编辑 3:添加了更多关于为什么不推荐的信息。
编辑 4:读错了,更新了答案。
关于python - 如何使用 Django 限制两列不具有相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40209137/