[Fixed]-Django Models Foreign key to same model I should not be able to add the same model in my example

1👍

You can override the model’s save() method:

class TestToExample(models.Model):
    example1 = models.ForeignKey(Test,related_name='example1')    
    example2 = models.ForeignKey(Test,related_name='example2')

    def save(self, force_insert=False, force_update=False, 
             using=None, update_fields=None):
        assert self.example1 != self.example2
        # Or:
        # if self.example1 == self.example2:
        #     raise WhateverError
        super(TestToExample, self).save(
            force_insert=force_insert, force_update=force_update, using=using, 
            update_fields=update_fields)

This will generally disallow you to ever have an invalid model state (with the exception of creating instances via bulk_create()). If you are saving instances via admin or through a model form, you might be better off overriding the model’s clean() method and raising a ValidationError there (see the documentation) in order to provide proper error messages instead of internal server errors:

class TestToExample(models.Model):
    ...
    def clean(self):
        if self.example1 == self.example2:
            raise ValidationError('example1 and example2 must be different')
        super(TestToExample, self).clean()

Leave a comment