2016-10-24 40 views
1

我有兩個整數列,並希望限制它們在一行中不具有相同的值。例如,如何使用Django限制兩列不具有相同的值?

id | type1 | type2 | 
------------------------ 
1 | 1 | 2 | 
2 | 1 | 3 | 
3 | 3 | 3 

第一行和第二行都可以,但第三行不應該存在。 如何在Django模型中添加此限制?

+0

無視我以前的鏈接,我認爲這是你在問什麼http://stackoverflow.com/questions/2281179/adding-extra-constraints-into-fields-in-django – serg

回答

1

模型做的是醜陋的/不推薦,你會需要像:

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 

,不建議,因爲用戶犯規得到什麼地方出了錯任何反饋,並取消保存,可能會導致錯誤的行爲。 (信號,重定向等可能會失敗)

如果可以的話,我會建議做一個表單驗證。

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:錯誤地閱讀,更新的答案。

相關問題