I have a django Model as follows:
class ModelName(models.Model): field_one = models.ForeignKey(Table_One, related_name="field_one") field_two = models.ForeignKey(Table_One, related_name="field_two")
unique_together can be used to make sure duplicate entries cant be made.
Eg, if for the above table:
unique_together = ['field_one', 'field_two']
Then you can enter values such as
field_two. However, you cannot make the same entry again. But this also allows entry
field_two, which according to my controller logic is the same as
A and B.
I need to make sure that if A and B are entered for the respective fields, B and A cannot be entered again.
How do I allow only entries of unique combinations?
Sample clean validation code,
from django.db.models import Q def clean(self): mn = ModelName.objects.filter(Q(field_one=self.field_one,field_two=field_two)|Q(field_one=self.field_two,field_two=field_one)) if mn.exists(): raise ValidationError('Already exist')
I would override the model's
clean method and raise a
ValidationError. It's a place where you can enforce extra constraints on your models.
Note however that this method will only be called after a ModelForm's is_valid().