Newtt
Newtt

Reputation: 6200

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?

Upvotes: 2

Views: 138

Answers (2)

zxzak
zxzak

Reputation: 9446

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

Upvotes: 1

Geo Jacob
Geo Jacob

Reputation: 6009

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

Upvotes: 1

Related Questions