django:外键触发的查询数与返回的对象数相同

django:外键触发的查询数与返回的对象数相同,django,django-models,Django,Django Models,我用OneToOne rel-to-User定义了一个UserProfile 基本上: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', unique=True) 当我查询UserProfile时,我惊讶地发现除了主查询之外,还有一个针对每个用户的查询 例如,我有6个用户/用户配置文件,在一个shell中,我执行以下操作: from django.db

我用OneToOne rel-to-User定义了一个UserProfile

基本上:

class UserProfile(models.Model):

    user = models.OneToOneField(User, related_name='profile', unique=True)
当我查询UserProfile时,我惊讶地发现除了主查询之外,还有一个针对每个用户的查询

例如,我有6个用户/用户配置文件,在一个shell中,我执行以下操作:

from django.db import connection
connection.queries = [] # reset

UserProfile.objects.all()
len(connection.queries) # 7 queries
查看这些查询,第一个查询与预期一样位于UserProfile表上,但是在User表上有6个查询,每个用户一个。这正常吗?我以为FK在访问时被查询过

SELECT "test_userprofile"."id", "test_userprofile"."created", "test_userprofile"."modified", "test_userprofile"."time_zone", "test_userprofile"."user_id"
FROM "test_userprofile" LIMIT 21

SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", 
       "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" 
FROM "auth_user" 
WHERE "auth_user"."id" = 1

SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", 
       "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" 
FROM "auth_user" 
WHERE "auth_user"."id" = 2

etc.

好吧,我终于明白为什么会这样。 在shell中直接运行UserProfile.objects.all时,会打印结果,并且我的UserProfile的_unicode__方法使用user self.users,它会触发其他请求