python - 如何使用 Django 限制两列不具有相同的值?

标签 python django database

我有两个整数列,并且想限制它们在一行中不具有相同的值。例如,

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/

相关文章:

database - Haskell 可以伪装成数据库吗?如果可以,怎么做?

python - 同步数据库时我应该使用什么密码?

python - Keras 模型 ValueError : Can not squeeze dim[1], 预期维度为 1,结果为 90

python - 使用装饰器包装一个接受可变数量参数的函数

python - Django 如何循环对象并在模板中显示变量

database - haskell "persistent"模型 : How to correctly define cross-reference?

python - matplotlib 堆积面积图中的动态标签

python - 没有表单的 Django 用户创建

python - Django : IndexError: list index out of range

database - Grails get()生成不完整的SQL