Prevent permutations of foreign keys in Django

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

I know 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 A for field_one and B for field_two. However, you cannot make the same entry again. But this also allows entry B for field_one and A for 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().

Validating objects

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:Prevent permutations of foreign keys in Django