[Django]-How to restrict two columns not to have the same value using Django?

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.

Leave a comment