首页 > 解决方案 > Django ModelMultipleChoiceField 给了我一个 ProgrammingError

问题描述

我想得到你的帮助,因为我遇到了一个让我觉得有点奇怪的问题。

我正在使用Django 1.11.16

我的 forms.py 文件中有这个类:

class PublicationStatForm(forms.Form):
    # publication_list = forms.ModelMultipleChoiceField(queryset=Publication.objects.all().order_by('pub_id'))
    publication_list = forms.ModelMultipleChoiceField(
        queryset=Publication.objects.all().order_by('pub_id'),
        label=_('Publication Choice'),
        widget=ModelSelect2Widget(
            model=Publication,
            search_fields=['pub_id__icontains', 'title__icontains'],
            attrs={'data-placeholder': "Please select publication(s)"}
        )
    )

    def __init__(self, *args, **kwargs):
        super(PublicationStatForm, self).__init__(*args, **kwargs)

然后,在我的 views.py 文件中:

class StatsView(TemplateView):
    """ Create statistics pageview """
    template_name = 'freepub/stats.html'
    form_class = PublicationStatForm

    def get_context_data(self, **kwargs):
        subtitle = _("Statistics")
        context_data = super(StatsView, self).get_context_data(**kwargs)
        context_data['form'] = self.form_class()
        ...
        return context_data

最后在我的模板中,我只有:

<form class="date-form" method="GET">
   <div class="row">
      <div class="col-md-7">
        {{ form.publication_list }}
      </div>
   </div>
   <input id="submit-date-stats" type="submit" class="btn btn-default" name="SearchPublicationPeriod"
               value="{% trans 'Submit' %}"/><br/>
</form>

我不明白为什么,当我的表格中有这条线时,它可以工作:

# publication_list = forms.ModelMultipleChoiceField(queryset=Publication.objects.all().order_by('pub_id'))

但是当我用这个替换这一行时:

publication_list = forms.ModelMultipleChoiceField(
    queryset=Publication.objects.all().order_by('pub_id'),
    label=_('Publication Choice'),
    widget=ModelSelect2Widget(
        model=Publication,
        search_fields=['pub_id__icontains', 'title__icontains'],
        attrs={'data-placeholder': "Please select publication(s)"}
    )
)

我得到这个问题:

Exception Type: ProgrammingError at /freepub/stats
Exception Value: relation "select_cache" does not exist
LINE 1: SELECT COUNT(*) FROM "select_cache"
                             ^

你有什么主意吗 ?

编辑:添加缓存设置

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
    },
    # "default": {
    #     "BACKEND": "django_redis.cache.RedisCache",
    #     "LOCATION": "redis://127.0.0.1:6379/1",
    #     "OPTIONS": {
    #         "CLIENT_CLASS": "django_redis.client.DefaultClient",
    #     }
    # },
    'select': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'select_cache',
        'TIMEOUT': None,
    }
}

# Set the cache backend to select2
SELECT2_CACHE_BACKEND = 'select'

标签: djangomodelchoicefieldmodelmultiplechoicefield

解决方案


问题在于您的缓存设置。

尽管您已经设置了数据库缓存后端,但您需要运行python manage.py createcachetable才能在数据库中实际创建它,类似于您migrate为常规模型更改或添加运行的方式 - 这也是错误看起来相似的原因,这让我无法迁移最初的路线。

DjangoProgrammingError异常是基本 DatabaseError 的扩展,因此它总是与数据库中的错误有关。(来源

如果您使用 redis 或其他 KV 存储缓存,则不会出现这种情况,因为它会自动插入它。由于 Django 数据库缓存使用同一数据库中的表,因此必须根据文档的这一部分创建该表。


推荐阅读