Django对__str__方法运行额外的查询

时间:2018-08-06 11:04:14

标签: python django database

我在Django中有这样的模型设置。

form django.contrib.auth.models import User


class Account(models.Model):
    user = models.OneToOneField(User)
    ...

    def __str__(self):
        return f'{self.user.first_name} {self.user.last_name}'


class SomeOtherModel(models.Model):
    account = models.ManyToManyField(Account)

现在我确实这样查询。

objects = SomeOtherModel.objects.filter(SOMETHING HERE).prefetch_related('account', 'account__user')

一切正常,但是在为帐户调用__str__的情况下,会像这样运行额外的查询

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" = 3

有人可以解释吗?

0 个答案:

没有答案