[英]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?
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)
As it is, under the Django Admin site, I'm able to select University A as the sister_university of University A (itself). 实际上,在Django Admin站点下,我可以选择University A作为University A(本身)的sister_university。 Is it possible to enforce some sort of a rule at the database level so a university object can never be its own sister_university?
是否可以在数据库级别强制执行某种规则,以使大学对象永远不能成为其自己的sister_university?
Alternatively, is there a better way of accomplishing what I'm trying to do? 或者,是否有更好的方法来完成我要尝试的操作?
What you want is a check
constraint, something like: 您想要的是一个
check
约束,例如:
alter table university
add constraint chk_non_self_ref check (id <> sister_university_id);
I'm not aware of a way to define this in Django models (but I'm guessing you can add it to a migration). 我不知道在Django模型中定义此方法的方法(但我猜您可以将其添加到迁移中)。
At the model level, you can override the clean()
method of your model to implement that check every time a University
instance is saved. 在模型级别,您可以覆盖模型的
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.