这是我的models.py:
的一部分class Media(TimeStampedModel):
name = models.CharField(max_length=20)
class Topic(TimeStampedModel):
medias = models.ManyToManyField(Media, through='TopicAndMedia')
class TopicAndMedia(models.Model):
topic = models.ForeignKey(Topic)
media = models.ForeignKey(Media)
order = models.IntegerField(default=0)
这是我的admin.py:
的一部分class TopicAndMediaInline(admin.TabularInline):
model = TopicAndMedia
class TopicAdmin(admin.ModelAdmin):
inlines = (TopicAndMediaInline, )
...
当我访问TOPIC管理网站时,它太慢了。这是django-debug-tool
的快照有许多重复的时间成本查询,例如select * from' topics_media'。我该如何解决这个问题?
答案 0 :(得分:0)
您正面临着django QuerySets的典型问题。您有这样的查询,因为当您访问事先未预取的相关对象时,您会进行额外的数据库命中。
了解更多https://docs.djangoproject.com/en/1.10/ref/models/querysets/#select-related和https://docs.djangoproject.com/en/1.10/ref/models/querysets/#prefetch-related
这应该可以解决您的问题
class TopicAdmin(admin.ModelAdmin):
inlines = (TopicAndMediaInline,)
def get_queryset(self, request):
qs = super(TopicAdmin, self).get_queryset(request)
qs = qs.prefetch_related('medias')
return qs