Django OneToOneField-我应该放在哪个模型中? [英] Django OneToOneField - in which model should I put it?

查看:151
本文介绍了Django OneToOneField-我应该放在哪个模型中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我们有以下模型.

Let's assume that we have the following models.

class A(Model): pass
class B(Model): pass

然后两者之间没有区别

在模型A中:b = OneToOneField(B, related_name=A.__name__)

在模型B中:a = OneToOneField(A, related_name=B.__name__)

那么我应该问自己哪些问题来决定是否将OTO放在一种或另一种模型中.我的意思是像has-a,is-a等.

So what questions should I ask myself to decide whether to put OTO in one model or another. I mean like has-a, is-a and so on.

推荐答案

放置一对一字段的位置实际上有所不同,因为删除的行为不同.删除对象时,具有与该对象一对一关系的其他任何对象都将被删除.相反,如果您删除一个包含一对一字段的对象(即,它引用其他对象,但其他对象没有引用该对象),则不会删除任何其他对象.

There actually is a difference in where you put the one-to-one field, because deletion behaves differently. When you delete an object, any other objects that had one-to-one relationships referencing that object will be deleted. If instead you delete an object that contains a one-to-one field (i.e. it references other objects, but other objects are not referencing back to it), no other objects are deleted.

例如:

class A(models.Model):
    pass

class B(models.Model):
    a = models.OneToOneField(A)

如果删除A,默认情况下B也将被删除(尽管您可以通过修改OneToOneField的on_delete参数来覆盖它,就像使用

If you delete A, by default B will be deleted as well (though you can override this by modifying the on_delete argument on the OneToOneField just like with ForeignKey). Deleting B will not delete A (though you can change this behavior by overriding the delete() method on B).

回到您的具有-a与is-a的初始问题,如果A有一个B,则B应该具有一对一字段(B仅在A存在的情况下才存在,但是A可以在没有B的情况下存在) ).

Getting back to your initial question of has-a vs. is-a, if A has a B, B should have the one-to-one field (B should only exist if A exists, but A can exist without B).

这篇关于Django OneToOneField-我应该放在哪个模型中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆