我有自己的城市模型(不是 django-cities-light),在 MySQL 表中有超过 2M 的记录。每次我开始输入自动完成字段时,htop 表上的 CPU 负载在 mysqld 进程上跳跃超过 200%,因此看起来脚本在每次自动完成时都请求表。
我想将表放入 memcache 以避免这种情况,这是我目前所拥有的:
autocomplete_light_registry.py
import autocomplete_light
from django.core.cache import cache, InvalidCacheBackendError
from cities.models import City
def prepare_choices(model):
key = "%s_autocomplete" % model.__name__.lower()
try:
qs = cache.get(key)
if cache.get(key): # return if not expired
return qs
except InvalidCacheBackendError:
pass
qs = model.objects.all() # populate cache
cache.set(key, qs, 60*60*24) # if expired or not set
return qs
class CityAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['city_name']
choices = prepare_choices(City)
autocomplete_light.register(City, CityAutocomplete)
但它仍然继续请求mysql。
有什么建议么?
更新
我试图在 django shell 中为城市表设置缓存,但该过程因分段错误消息而中断。
>>> from django.core.cache import cache
>>> qs = City.objects.all()
>>> qs.count()
2246813
>>> key = 'city_autocomplete'
>>> cache.set(key, qs, 60*60*24)
Segmentation fault
但是我能够将较小的表放入缓存中,我希望能够克服这个问题,所以仍然需要答案。