Django Admin超慢选择单个记录

时间:2019-07-18 07:38:40

标签: django django-models django-admin

我有一个Pick模型,当我在Django Admin中选择一条记录时,需要花费一定的时间(大约20秒)来检索记录(大约70k)。但是,当我尝试创建/保存记录时很快。我已经添加了索引以尝试加快检索速度,但是我真的不知道该怎么做

class Pick (models.Model):
    team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, db_index=True)
    contest_entry=models.ForeignKey(ContestEntry, on_delete=models.CASCADE, db_index=True)
    game_round=models.ForeignKey(GameRound, on_delete=models.CASCADE, db_index=True)

    objects = DataFrameManager()

    def __str__(self):
        return f'%s %s' % (self.contest_entry, self.game_round)

    class Meta:
        unique_together = ['user', 'contest_entry', 'game_round']
        ordering = ['contest_entry','game_round','user','team']
        index_together = [["user", "contest_entry", 'game_round'],]
        indexes = [
            models.Index(fields=['user', 'contest_entry', 'game_round']),
            models.Index(fields=['game_round'], name='game_round_idx'),
            models.Index(fields=['contest_entry'], name='contest_entry_idx'),
        ]

class PickAdmin(admin.ModelAdmin):
    model = Pick
    list_filter= (
        ('user', RelatedDropdownFilter),
        ('contest_entry__contest', RelatedDropdownFilter),
        ('game_round', RelatedDropdownFilter)
    )

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('user','contest_entry','game_round')
admin.site.register(Pick, PickAdmin)

如何在此处提高性能?

3 个答案:

答案 0 :(得分:1)

键是在管理类上指定raw_id_fields。用于外键关系的默认<select>小部件会导致检索和呈现所有选项的大量开销。

class PickAdmin(admin.ModelAdmin):
    model = Pick
    list_filter= (
        ('user', RelatedDropdownFilter),
        ('contest_entry__contest', RelatedDropdownFilter),
        ('game_round', RelatedDropdownFilter)
    )
    raw_id_fields = ('user', 'contest_entry', 'game_round',)

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('user','contest_entry','game_round')

答案 1 :(得分:0)

我的猜测是,花很长时间渲染模型的ForeignKey字段的下拉列表。

我建议您通过安装Django工具栏或启用数据库服务器中的日志查看执行的SQL查询。

答案 2 :(得分:0)

您可以通过将select_related用于外键https://docs.djangoproject.com/en/2.2/ref/models/querysets/#select-related

来改进查询