3

I have two integer columns, and want to restrict them not to have the same value within a row. For example,

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

The first and second rows are okay, but the third one should not exist. How to add this restriction in Django model?

MaxHeap
  • 1,138
  • 2
  • 11
  • 20
  • disregard my previous link, i think this one is what you are asking http://stackoverflow.com/questions/2281179/adding-extra-constraints-into-fields-in-django – serg Oct 24 '16 at 01:57

1 Answers1

3

Doing in in the model is ugly/not recommended, you would need something like:

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 

It is not advised because the user doesnt get any feedback on what went wrong and cancelling the save might result in incorrect behaviours. (signals, redirects, etc.. might fail)

I would advise to do in as a form validation instead if you can.

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")

EDIT 1: Fix indent.

EDIT 2: Added Form Validation example.

EDIT 3: Added more info on why it is not recommended.

EDIT 4: Read wrongly, updated answer.

Jon Loo
  • 121
  • 5