2012-12-14 67 views
0

我有ManyToManyFielddjango.contrib.auth.models.PermissionDjango的ManyToManyField到權限

的問題是,當我打開編輯我的模型記錄的管理,數據庫的請求數量是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 ••• 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

,看見你已被使用一些PermissionManager,但不知道究竟是什麼發生,如何讓它在我的經理

回答

2

是的,你可以使用prefetch_relatedQuerySet method,這是它預定的目的!

這應該會將查詢開銷減少到僅針對所有相關對象的一個​​查詢。

+0

當然,但確切地說。我嘗試了一些參數組合,但不能使它變成 –

+0

@ju。你是否試過'返回超級(RoleManager,self).get_query_set()。select_related('organization')。prefetch_related('permissions__content_type')'? –

+0

是:(但我可以肯定地告訴你今天 –

0

調試工具欄可以提出這個請求,如果你正在使用它。