[英]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 have the following in my app: 我的应用程序中有以下内容:
class University(models.Model):
...
sister_university = models.OneToOneField('self', related_name =
'university_sister_university',
blank=True, null=True,
on_delete=models.SET_NULL)
I only want a university to be related to one other university in both directions of that relationship. 我只希望大学在这种关系的两个方向上与另一所大学有关。
For example, in the database, if I select university A as the sister_university of university B, I only want to be allowed to select university B as the sister_university under university A also. 例如,在数据库中,如果我选择大学A作为大学B的姐妹大学,我只希望被允许选择大学B作为大学A下的姐妹大学。 However, as it is, that second relationship is not enforced.
但是,实际上,第二种关系没有得到强制执行。
For example: Right now, under the Django Admin site, if I first select university A as the sister university of university B, I am still able to select any other university as the sister university of the university A object. 例如:现在,在Django Admin网站下,如果我首先选择大学A作为大学B的姐妹大学,我仍然可以选择任何其他大学作为大学A姐妹大学的对象。 I'm not constrained to only selecting university B.
我不仅限于选择大学B.
Is it possible to enforce that uniqueness at the database level? 是否可以在数据库级别强制执行该唯一性? Is there a better way of accomplishing what I'm trying to do?
有没有更好的方法来完成我想要做的事情?
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: 您可以通过覆盖
University
模型的save()
方法来完成此任务:
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 : 我从来没有做过这种事情,但我认为你可以通过这种方式完成这个过程:
You can use Options.unique_together
and set your university_A and university_B as a unique pair. 您可以使用
Options.unique_together
并将university_A和university_B设置为唯一对。
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) : 在你的models.py文件中,你应该有这样的东西(可能有一些问题,但想法就在那里):
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/ 你应该在那里找到宝贵的细节: 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. 我从未尝试过这个命令,但它似乎根据你的上下文解决了你的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.