ORM Relationship

Relationshipmethodsql
1:1select_related()join
N:1select_related()join
1:Nprefetch_related()in
N:Nprefetch_related()in

Example

  • User:UserSetting = 1:1
  • User:Comment = 1:N
class User(models.Model):
    name = models.CharField(max_length=32, default="foo", blank=False)

class UserSetting(models.Model):
    user = models.OneToOneField(User, related_name="karma")
    age = models.IntegerField(null=False, default=0)

class Comment(models.Model):
    user = models.ForeignKey(User, related_name="comments")
    content = models.CharField(max_length=140, null=False, default="")

select_relatedの挙動

Here, the relationship when each select_related() is done is as follows.

Relationshipyourselfjoin targetquery
1:1'UserUserSettingLEFT OUTER JOIN
1':1UserSettingUserINNER JOIN
M:1CommentUserINNER JOIN
1:MUserCommentx
  • one to one' is left outer join since there is a possibility that UserSetting doesn't exist
  • one to many is impossible