Django数据库搜索未返回匹配行反而新增搜索值列问题求助
问题原因及修复方案
1. 前端渲染逻辑错误(直接导致所有行VendorName列显示搜索值)
你的HTML表格里,VendorName列写的是{{finder}},也就是把你输入的搜索值直接渲染到了每一行的这个位置,自然所有行都会显示你搜的内容,和实际数据无关。应该改为读取每一行数据里的VendorName字段。
2. 搜索逻辑完全未生效
你在视图里虽然执行了invoiceapi.objects.filter(...)拿到了匹配结果invoiceuser,但传给模板的还是全量的原始API数据table_data,压根没用到筛选后的结果,所以根本不会过滤行。同时你筛选用的字段PBK_Desc在invoiceapi模型里根本不存在,要按供应商名称筛选应该用模型里定义的Vendor_Name字段。
3. 数据存储逻辑存在多处错误
- 你定义的
invoiceapi模型里供应商字段是Vendor_Name,但你存数据的时候字典key写的是VendorName,字段不匹配,会导致该字段存空 Userbase模型里没有定义country字段,你POST请求里给userb.country赋值会报错- 每次访问页面都会重复请求API并往
invoiceapi表里插入重复数据,会导致表数据冗余爆炸 - 两个相同的
if request.method == 'POST'判断逻辑冗余,应该合并
修正后的代码
models.py(注意字段名统一)
# 筛选条件存储模型 class Userbase(models.Model): Vendor_Name = models.CharField(max_length=255, null=True) Region = MultiSelectField(choices=CHOICES) Area = MultiSelectField(choices=AREACHOICES) # API数据存储模型 class invoiceapi(models.Model): Vendor_Name = models.CharField(max_length=155, null=True) area = models.CharField(max_length=155, null=True) country = models.CharField(max_length=155, null=True)
views.py(修正逻辑)
def homeview(request): userb = Userbase.objects.all() # 未提交搜索时默认用全量API数据 table_data = requests.get('http://127.0.0.1:1500/api/').json() finder = None if request.method == 'POST': # 保存筛选条件 new_filter = Userbase() new_filter.Area = request.POST.getlist('Area') new_filter.Vendor_Name = request.POST.get('Vendor_Name') new_filter.save() # 处理搜索逻辑 finder = request.POST.get('Vendor_Name') # 按Vendor_Name模糊匹配,拿到筛选后的数据 filtered_invoice = invoiceapi.objects.filter(Vendor_Name__icontains=finder) # 把筛选后的结果转成和API返回结构一致的格式传给模板,替换原来的全量table_data table_data = filtered_invoice.values('area', 'country', 'Vendor_Name') return render(request, 'home.html', { 'userb': userb, 'table_data': table_data, 'finder': finder }) # 非POST请求的情况,插入API数据前可以先清空避免重复,可根据自身需求调整 # invoiceapi.objects.all().delete() for new_data in table_data: invoiceapi.objects.create( area=new_data['area'], country=new_data['country'], Vendor_Name=new_data['VendorName'] # 字段名和模型对齐 ) return render(request, 'home.html', { 'userb': userb, 'table_data': table_data, 'finder': finder })
HTML部分(仅需修正表格渲染字段)
<!-- 其余代码不变,仅修改tbody部分 --> <tbody> {% for item in table_data %} <tr> <td>{{item.area}}</td> <td>{{item.country}}</td> <td>{{item.Vendor_Name}}</td> </tr> {% endfor %} </tbody>
内容的提问来源于stack exchange,提问作者imran_44
相关产品推荐
相关产品推荐

