我的模型包含ManyToManyField
到django.contrib.auth.models.Permission
问题是当我打开以在admin中编辑我的模型记录时,数据库请求的数量是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
可能我必须使用经理来解决这个问题吗?
我看了https://github.com/django/django/blob/master/django/contrib/auth/models.py
并看到Permission正在使用一些PermissionManager,但不确定究竟发生了什么,以及如何在我的经理中进行此操作
答案 0 :(得分:2)
是的,你可以使用prefetch_related
QuerySet
method,这是它的预期用途!
这应该将查询开销减少到只有一个查询所有相关对象。
答案 1 :(得分:1)
如果您正在使用它,调试工具栏可以发出此请求。