0

Suppose I have a Django model with two fields one and two:

class MyModel(models.Model):
    one = models.CharField(max_length=100, unique=True)
    two = models.CharField(max_length=100)

unique=True means if I try to put in a row with one="one" when another such row already exists, a unique constraint will be violated.

How would I make a Django constraint that says if there is a row with one="one", then I can't put in a row with two="one"?

This does seem related to this question and this answer, but I don't quite see the answer to my question.

dfrankow
  • 20,191
  • 41
  • 152
  • 214
  • you can create a custom validator which will get called on the save method and there you can query the existence of that value and decide to move forward. – Hemal Patel Aug 03 '23 at 22:41
  • You can use a [constraint expression](https://docs.djangoproject.com/en/4.2/ref/models/constraints/#expressions) but your question is too vague to be answered. – Selcuk Aug 03 '23 at 23:18

1 Answers1

1

For custom validation like this I've found it best to override the save method, as @Hemal Petal mentioned:

models.py from django.core.exceptions import ValidationError

def save(self, *args, **kwargs):

    if MyModel.objects.filter(
        two=self.one
    ).exists():
        raise ValidationError(f'{self.one} already exists in column two!')
    
    return super().save(*args, **kwargs)
Daniel
  • 3,228
  • 1
  • 7
  • 23
  • Thanks for this answer, that's a good recommendation. Yes, I have overridden the save method. However, my question is asking if it's possible to write a constraint. The answer may be no. – dfrankow Aug 04 '23 at 13:47