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

使用django-datatables-view搜索外键字段报错Related Field got invalid lookup: istartswith

报错原因

该错误由Django ORM查询规则触发:istartswith是字符串类型字段的模糊查询条件,你在视图的columns配置中直接使用了外键字段customer,框架在处理搜索时会默认对该字段追加istartswith查询,而外键本身是关系对象,不支持该查询条件,因此抛出错误。前端配置的customer.first_name未和后端字段规则对齐,无法生效。

修复步骤

1. 后端视图修改

调整columns与order_columns配置,使用Django ORM双下划线语法指定外键关联的具体字段:

class CustomerListJsonView(LoginRequiredMixin, BaseDatatableView):
    """This is the view used by Datatables.net to render the Datatable"""
    # The model we're going to show
    model = Customer

    # 替换外键字段customer为关联的具体字段customer__first_name
    columns = ['id', 'customer__first_name', 'amount', 'date_time']   

    # 排序字段同步替换
    order_columns = ['id', 'customer__first_name', 'amount', 'date_time']
    max_display_length = 100
    
    def render_column(self, row, column):
        # We want to render phone number as a custom column        
        if column == 'date_time':                                    
            return row.date_time.strftime('%b %d %Y %I:%M %p') 
        else:            
            return super(CustomerListJsonView, self).render_column(row, column)  

2. 前端配置修改

对齐后端的字段命名,调整对应列的fields配置:

var customerTable = $(DOMstrings.customerTable ).DataTable({        
      "processing": true,        
      "searching": true,
      'pageLength': 30,
      "scrollY": 500,
      "responsive": true, 
      "ordering": true, 
      "paging": true,   
      "lengthChange": true,  

      "ajax": {
          "url": customerListURL,                
      },
      "serverSide": true,

      "columns": [        
          { "fields": "id" },                   
          { "fields": "customer__first_name"}, // 和后端字段对齐
          { "fields": "amount" },
          { "fields": "date_time" },                                
      ],
      dom: 'Bfrtip',
      buttons: [
          'colvis',            
          'pageLength',
      ],        
  });
可选补充配置

如果某列对应外键字段不需要支持搜索,可直接在前端对应列配置"searchable": false,框架就不会为该字段生成搜索查询条件,也可避免该错误。

内容的提问来源于stack exchange,提问作者David.B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:15:03