2

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?

Newtt
  • 6,050
  • 13
  • 68
  • 106

2 Answers2

1

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

zxzak
  • 8,985
  • 4
  • 27
  • 25
1

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')
Geo Jacob
  • 5,909
  • 1
  • 36
  • 43
  • This works but `ValidationError` is giving me `'ValidationError' object has no attribute 'error_dict'` error. – Newtt Jul 31 '15 at 08:09