以 Django 形式缓存 ModelChoiceField 或 ModelMultipleChoiceField 的查询集选择 [英] Caching queryset choices for ModelChoiceField or ModelMultipleChoiceField in a Django form

查看:24
本文介绍了以 Django 形式缓存 ModelChoiceField 或 ModelMultipleChoiceField 的查询集选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Django 表单中使用 ModelChoiceFieldModelMultipleChoiceField 时,有没有办法传入一组缓存的选项?目前,如果我通过 queryset 参数指定选项,则会导致数据库命中.

When using ModelChoiceField or ModelMultipleChoiceField in a Django form, is there a way to pass in a cached set of choices? Currently, if I specify the choices via the queryset parameter, it results in a database hit.

我想使用 memcached 缓存这些选择,并在显示具有此类字段的表单时防止对数据库的不必要命中.

I'd like to cache these choices using memcached and prevent unnecessary hits to the database when displaying a form with such a field.

推荐答案

您可以覆盖 QuerySet 中的all"方法类似的东西

You can override "all" method in QuerySet something like

from django.db import models
class AllMethodCachingQueryset(models.query.QuerySet):
    def all(self, get_from_cache=True):
        if get_from_cache:
            return self
        else:
            return self._clone()


class AllMethodCachingManager(models.Manager):
    def get_query_set(self):
        return AllMethodCachingQueryset(self.model, using=self._db)


class YourModel(models.Model):
    foo = models.ForeignKey(AnotherModel)

    cache_all_method = AllMethodCachingManager()

然后在使用表单之前更改字段的查询集(例如,当您使用表单集时)

And then change queryset of field before form using (for exmple when you use formsets)

form_class.base_fields['foo'].queryset = YourModel.cache_all_method.all()

这篇关于以 Django 形式缓存 ModelChoiceField 或 ModelMultipleChoiceField 的查询集选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆