我遇到一个m2m字段的问题,该字段使用带有admin和inlines的中间模型('through')。这是代码:
# MODELS
class Engagement(models.Model):
parent_engagement = models.ForeignKey('self', blank=True, null=True, related_name='child_engagements')
title = models.CharField('Engagement title', max_length=200)
...
# client
client = models.ForeignKey(Client, related_name='engagements')
primary_point_of_contact = models.ForeignKey(
ClientContact, null=True, blank=True,
related_name='engagements_for_which_point_of_contact'
)
additional_point_of_contacts = models.ManyToManyField(
ClientContact,
through='AdditionalPointOfContact'
)
.... # other fields
class ClientContact(models.Model):
first_name = models.CharField(max_length=200, blank=True)
last_name = models.CharField(max_length=200, blank=True)
jobtitle = models.CharField(max_length=200, blank=True)
company = models.ForeignKey(Client, null=True, blank=True)
class AdditionalPointOfContact(models.Model):
engagement = models.ForeignKey("Engagement", related_name='additional_points_of_contact')
client_contact = models.ForeignKey("ClientContact")
description = models.CharField(max_length=500, blank=True)
def __unicode__(self):
return self.client_contact.__unicode__()
# ADMIN
class EngagementAdmin(ChaosDefaultAdmin):
....
inlines = [
ScopeServiceElementAdmin,
AdditionalPointOfContactInlineAdmin
]
list_display = (...
class AdditionalPointOfContactInlineAdmin(admin.TabularInline):
model = AdditionalPointOfContact
fieldsets = [
('', {
'fields': (('client_contact',),
('description',),)
}),
]
extra = 0
min_num = 0
根据django-debug-toolbar
,sql选项卡显示8382个查询,而注释AdditionalPointOfContactInlineAdmin
则减少到10个查询,因此出现了问题。
我可能会覆盖AdditionalPointOfContactInlineAdmin
的get_queryset方法,但我不确切知道如何以及为什么。有什么建议吗?
答案 0 :(得分:0)
尝试覆盖EngagementAdmin.get_queryset():
class EngagementAdmin(ChaosDefaultAdmin):
def get_queryset(self, request):
qs = super(EngagementAdmin, self).get_queryset(request)
return qs.prefetch_related('additional_points_of_contact')
# or
# return qs.prefetch_related('additional_points_of_contact__client_contact')