开发者

Django: following the reverse direction of the one-to-one relationship

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!


Storing the id in one of the tables is enough.

In case 1, (a.b) the SQL generated would be

SELECT * from B where b.id = a.b_id

and in case 2, the SQL would be:

SELECT * from A where a.b_id = b.id

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.


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:

# Table B
| id | bAtt    |
----------------
|  1 | oh, hi! |
|  2 | hello   |

# Table A
| id | b_id |
-------------
| 3  |  1   |
| 4  |  2   |

Then a join on B.id = b_id will create the following tuples:

| B.id | B.bAtt  | A.id |
------------------------
|  1   | oh, hi! |  3   |
|  2   | hello   |  4   |

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.


Other object-relational mappers require you to define relationships on both sides. The Django developers believe this is a violation of the DRY (Don't Repeat Yourself) principle, so Django only requires you to define the relationship on one end.

Always take a look at the doc ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜