I have a OneToOne relationship between two objects of the same class in a Django app. Is it possible to enforce the uniqueness of this relationship?
I think that what you need is to make this relationship symmetric.
You can accomplish this by overriding the save()
method of the University
model:
def save(self, *args, **kwargs): super(University, self).save() if self.sister_university: self.sister_university.sister_university = self
I never did this kind of things, but I think that you can make this process through this way :
Method : unique_together()
You can use Options.unique_together
and set your university_A and university_B as a unique pair.
unique_together = ("university_A", "university_B")
In your models.py file, you should have something like this (with maybe some issues, but the idea is there) :
class University(models.Model): ... university = models.ForeignKey('self', on_delete=models.CASCADE) sister_university = models.ForeignKey('self', on_delete=models.CASCADE) class Meta: unique_together = (('university','sister_university'),)
You should find precious details there : https://docs.djangoproject.com/en/2.0/ref/models/options/
I never tried this command, but it seems to solve your issue according to your context.