Django:遵循一对一关系的相反方向
我对 Django 建模一对一关系的方式有疑问。
假设我们有2个模型:A和B:
class B(models.Model):
bAtt = models.CharField()
class A(models.Model):
b = models.OneToOneField(B)
在创建的表A中,有一个字段“b_id”,但在Django创建的表B中没有“a_id”字段。
因此,给定一个 A 对象,只需通过 A 行的“b_id”列即可检索相应的 B 对象,这当然很快。
但是 Django 如何在给定 B 对象的情况下检索 A 对象呢?
最坏的情况是扫描A表以在“b_id”列中搜索B.id。如果是这样,我们是否建议在B模型和表中手动引入一个额外的字段“a_id”?
提前致谢!
I have a question about the way Django models the one-to-one-relationship.
Suppose we have 2 models: A and B:
class B(models.Model):
bAtt = models.CharField()
class A(models.Model):
b = models.OneToOneField(B)
In the created table A, there is a field "b_id" but in the table B created by Django there is no such field as "a_id".
So, given an A object, it's certainly fast to retrieve the corresponding B object, simply through the column "b_id" of the A's row.
But how does Django retrieve the A object given the B object?
The worst case is to scan through the A table to search for the B.id in the column "b_id". If so, is it advisable that we manually introduce an extra field "a_id" in the B model and table?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将 id 存储在其中一张表中就足够了。
在情况 1 中,(ab) 生成的 SQL 为
: 在情况 2 中,生成的 SQL 为:
您可以看到,两种方式生成的 SQL 都很相似,并且分别取决于它们的大小。
几乎在所有情况下,索引就足够了,并且只需 1 个 id 即可获得良好的性能。
Storing the id in one of the tables is enough.
In case 1, (a.b) the SQL generated would be
and in case 2, the SQL would be:
You can see that the SQLs generated either way are similar and depend respectively on their sizes.
In almost all cases, indexing should suffice and performance would be good with just 1 id.
请务必查看文档;)
Always take a look at the doc ;)
Django 通过 SQL 中的 JOIN 检索字段,有效地将两个表中 b_id 与 B.id 匹配的行融合在一起。
假设您有以下表格:
然后
B.id = b_id
上的联接将创建以下元组:无论您从哪一侧输入关系,Django 都会执行此操作,因此同样有效:) 如何数据库实际上执行连接取决于数据库实现,但以一种或另一种方式,它必须遍历每个表中的每个元素并比较连接属性。
Django retrieves the field through a
JOIN
in SQL, effectively fusing the rows of the two tables together where the b_id matches B.id.Say you have the following tables:
Then a join on
B.id = b_id
will create the following tuples:Django does this no matter which side you enter the relation from, and is thus equally effective :) How the database actually does the join depends on the database implementation, but in one way or another it has to go through every element in each table and compare the join attributes.