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

Django对接MongoDB含空格字段查询报错的解决方案咨询

Django过滤含空格的MongoDB字段时保留原字段名的解决方案

问题场景

开发者基于Python开发日常自动化项目,接入MongoDB后用Django搭建GUI,在视图中做数据过滤时遇到字段名含空格的问题:执行过滤操作触发FieldError,无法解析带空格的字段名,但不想修改MongoDB中已批量设置的带空格字段名。

错误信息

django.core.exceptions.FieldError: Cannot resolve keyword '' into field. Choices are: NP Title ID, Product Code, Product Type, _id

相关代码

模型代码

class Railway_Products(models.Model):
    _id = models.ObjectIdField(name='_id', editable=False)
    np_title_id = models.CharField(name='NP Title ID', max_length=15)
    product_type = models.CharField(name='Product Type', max_length=15)
    product_code = models.CharField(name='Product Code', max_length=15)

    class Meta:
        db_table = "Products"
        verbose_name_plural = "products"

视图代码

class Railway_Products_ListView(generic.ListView):
    model = Railway_Products
    context_object_name = 'product_list'
    queryset = model.objects.filter(name='NP Title ID',__icontains='PPSA')

问题核心出在过滤代码行:

queryset = model.objects.filter(name='NP Title ID',__icontains='PPSA')

通过name参数传入带空格的字段名不被Django识别,尝试用变量替代字段名也无效。测试将字段名改为无空格的NPTitleID后过滤正常,但开发者希望保留MongoDB原字段名。

解决方案

利用Django模型字段的db_column参数,映射数据库中带空格的字段,同时在模型中使用合法的无空格标识符作为代码调用的字段名:

修改后的模型代码

class Railway_Products(models.Model):
    _id = models.ObjectIdField(name='_id', editable=False)
    # db_column指定MongoDB中带空格的字段名,name设置代码中可用的合法字段名
    np_title_id = models.CharField(name='NPTitleID', db_column='NP Title ID', max_length=15)
    product_type = models.CharField(name='ProductType', db_column='Product Type', max_length=15)
    product_code = models.CharField(name='ProductCode', db_column='Product Code', max_length=15)

    class Meta:
        db_table = "Products"
        verbose_name_plural = "products"

修改后的视图代码

class Railway_Products_ListView(generic.ListView):
    model = Railway_Products
    context_object_name = 'product_list'
    queryset = model.objects.filter(NPTitleID__icontains='PPSA')

验证结果

修改后视图可正常返回预期结果且无报错,仅需在Django管理端将过滤器名称从NP Title ID改为NPTitleID,无需改动MongoDB中的字段名,实现成本远低于修改数据库字段。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:43:30