Sandeep Kushwaha
Sandeep Kushwaha

Reputation: 25

unique constraint on the basis of foreign model field value django

I have three model in django applications.

for example:

class A(models.Model):
    field1 = models.CharField(..)
    field2 = models.CharField(...)

class B(models.Model):
    field1 = models.CharField(..)
    field2 = models.CharField(...)

class C(models.Model):
    field1 = models.ForeignKey(A, ..)
    field2 = models.ForeginKey(B, ..)

Now I want to make sure that value of field1 and field2 is unique together. I know i can use unique_togher = ('field1', 'field2'). but it only compare object id of model A and object id of model B.

But here actually i want to compare with actual field2 value of modelB

somethings like,

unique_together = ('field1', 'field2.field2')

After suggestion of @Arvind Kumar i edited my model but still I'm facing error. Here is my model after edit.

Model Image

Error Image

Upvotes: 0

Views: 611

Answers (1)

Arvind Kumar
Arvind Kumar

Reputation: 973

You can not put unique constraints across the relations. You can only put columns belonging to the current Model only in unique constraints or unique_together. However, you can try the following approach

class C(models.Model):
    field1 = models.ForeignKey(A, ..)
    field2 = models.ForeginKey(B, ..)

def validate_unique(self, exclude=None):
        qs = C.objects.filter(field1=self.field1)
        if qs.filter(B__field2=self.field2).exists():
            raise ValidationError('Fields must be unique')

        models.Model.validate_unique(self, exclude=exclude)

Also, note that this function will not be called automatically while saving the objects of model C, so you will have to call it explicitly.

Upvotes: 2

Related Questions