1

我有一个ManyToManyField模型django.contrib.auth.models.Permission

问题是当我在管理员中打开编辑我的模型记录时,数据库请求的数量是 241

class RoleManager(models.Manager):

    def get_query_set(self):
        return super(RoleManager, self).get_query_set().select_related('organization')

class Role(models.Model):

    name = models.CharField(u'Name', max_length = 80)
    organization = models.ForeignKey(Organization)
    permissions = models.ManyToManyField(Permission, blank = True)

    objects = RoleManager()

    def __unicode__(self):
        return u'{name} in {organization}'.format(name = self.name, organization = self.organization.name)

235 个 SELECT 是:

SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 8
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 8
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 8
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 68
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 69
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 69
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 69
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 9
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 9
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 9
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 10
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 10
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 10
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = 17

可能我必须使用 Manager 来解决这个问题吗?

我看了https://github.com/django/django/blob/master/django/contrib/auth/models.py

并看到 Permission 正在使用一些 PermissionManager,但不确定到底发生了什么,以及如何在我的经理中实现

4

2 回答 2

3

是的,您可以使用该prefetch_related QuerySet方法,这就是它的预期目的!

这应该会将您的查询开销减少到对所有相关对象的一次查询。

于 2012-12-14T15:21:06.143 回答
1

调试工具栏可以发出这个请求,如果你正在使用它。

于 2014-02-05T14:54:13.780 回答