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

如何在Django Admin中配置可编辑的ManyToMany字段面板?

解决Django Admin中ManyToManyField编辑组件配置错误的问题

问题根源

你在CollectionAdmin里配置filter_horizontal=('collections',)触发错误,核心原因是**collections不是Collection模型本身的字段**——它是Product模型中反向关联Collection的名称(由related_name='collections'定义)。而Collection模型自身的ManyToMany字段实际名为product。

修正方案

修改admin.py中的CollectionAdmin类,将filter_horizontal的参数替换为Collection模型实际的字段名product:

class CollectionAdmin(admin.ModelAdmin):
    filter_horizontal = ('product',)

admin.site.register(Collection, CollectionAdmin)

可选优化

如果需要在Product的Admin页面也能直接编辑关联的Collection,可以给Product添加对应的Admin配置:

class ProductAdmin(admin.ModelAdmin):
    filter_horizontal = ('collections',)

admin.site.register(Product, ProductAdmin)

这里使用collections是合法的,因为它是Product模型通过related_name定义的反向关联字段。

内容的提问来源于stack exchange,提问作者Hong Jun Woo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 10:33:13