在 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.
推荐答案
可以覆盖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屋!