You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Admin自定义发布菜谱过滤器报错admin.E116求助

Django Admin自定义用户菜谱发布状态过滤器错误排查

问题场景

开发菜谱社交网络项目时,尝试在Django Admin的UserAdmin中添加自定义过滤器,用于筛选是否发布过菜谱的用户,但执行makemigrations时触发错误:

ERRORS:
<class 'recipes.admin.UserAdmin'>: (admin.E116) The value of 'list_filter[2]' refers to 'UserHasRecipeFilter', which does not refer to a Field.

错误原因

在list_filter配置中,错误地将自定义过滤器类UserHasRecipeFilter用字符串引号包裹,Django会将其当作模型字段名去查找,而非识别为自定义过滤器类对象。此外需确保过滤器类已正确导入到当前admin模块中。

修复步骤

  1. 移除过滤器类的引号:在list_filter中直接引用类对象,不要用字符串包裹
  2. 确保过滤器类已导入:如果UserHasRecipeFilter定义在其他文件,需在admin文件顶部导入

修正后的UserAdmin代码

# 确保已导入自定义过滤器类(根据实际文件路径调整)
from .filters import UserHasRecipeFilter

@admin.register(UserProfile)
class UserAdmin(UserAdmin):
    list_filter = ('is_active', UserHasRecipeFilter,)

可选优化

自定义过滤器的queryset方法可优化,避免重复调用annotate:

class UserHasRecipeFilter(admin.SimpleListFilter):
    title = _('Posted recipes')
    parameter_name = 'posted_recipes'

    def lookups(self, request, model_admin):
        return (
            ('yes', _('Yes')),
            ('no', _('No')),
        )

    def queryset(self, request, queryset):
        annotated_qs = queryset.annotate(recipes_count=Count('recipes'))
        if self.value() == 'yes':
            return annotated_qs.filter(recipes_count__gt=0)
        elif self.value() == 'no':
            return annotated_qs.filter(recipes_count=0)
        return queryset

内容的提问来源于stack exchange,提问作者moonsund

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 09:51:08