How can you create a unique constraint for two ForeignKeys in Django referring to the same model?

1 Answers
Answered by suresh

To create a unique constraint for two ForeignKeys in Django referring to the same model, you can use the `UniqueConstraint` class in the Django models module. Here is an example implementation:

```python
from django.db import models
from django.db.models import UniqueConstraint

class MyModel(models.Model):
related_model1 = models.ForeignKey('RelatedModel', on_delete=models.CASCADE, related_name='related_model1')
related_model2 = models.ForeignKey('RelatedModel', on_delete=models.CASCADE, related_name='related_model2')

class Meta:
constraints = [
UniqueConstraint(fields=['related_model1', 'related_model2'], name='unique_constraint')
]

class RelatedModel(models.Model):
# Your RelatedModel definition here
```

In this example, `MyModel` has two ForeignKeys each referring to the `RelatedModel`. The `UniqueConstraint` is used to ensure that the combination of `related_model1` and `related_model2` is unique in the database.

By adding this unique constraint in the Django models, you can restrict the database from having duplicate combinations of the two ForeignKeys pointing to the same model, helping maintain data integrity.

Answer for Question: How can you create a unique constraint for two ForeignKeys in Django referring to the same model?