在Django表单中为ModelChoiceField或ModelMultipleChoiceField缓存查询选项 [英] Caching queryset choices for ModelChoiceField or ModelMultipleChoiceField in a Django form
问题描述
在Django表单中使用ModelChoiceField 或 ModelMultipleChoiceField 时,是否有方法传递缓存的选项?目前,如果我通过 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.
推荐答案
您可以覆盖all QuerySet
类似于
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()
然后在表单使用之前更改字段的查询(例如,当您使用formets时)
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屋!