[英]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?
[英]In Django, for a OneToOne relationship between two objects of the same class, can an object be prevented from referring to itself at the db level?
我的應用程序中包含以下內容:
class University(models.Model):
...
sister_university = models.OneToOneField('self',
related_name =
'university_sister_university',
blank=True, null=True,
on_delete=models.SET_NULL)
實際上,在Django Admin站點下,我可以選擇University A作為University A(本身)的sister_university。 是否可以在數據庫級別強制執行某種規則,以使大學對象永遠不能成為其自己的sister_university?
或者,是否有更好的方法來完成我要嘗試的操作?
您想要的是一個check
約束,例如:
alter table university
add constraint chk_non_self_ref check (id <> sister_university_id);
我不知道在Django模型中定義此方法的方法(但我猜您可以將其添加到遷移中)。
在模型級別,您可以覆蓋模型的clean()
方法,以在每次保存University
實例時實施該檢查。
def clean(self):
if self.sister_university.id == self.id:
raise ValidationError('A university object can never be its own sister_university.')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.