首页 > 解决方案 > 检查变量是否是queryset django中的列表

问题描述

我正在尝试检查我的变量是否在我的查询集中。

来自表格的变量:

def magazine_new(request):
    if form.is_valid():
        post.mag_no = request.POST.get('mag_no')

        post.cn1 = request.POST.get('cn1')
        post.cn2 = request.POST.get('cn2')
        post.cn3 = request.POST.get('cn3')
        post.cn4 = request.POST.get('cn4')

然后,我想检查这个 mag_no 中是否存在这些 CN
我试过这个,但是没有用。

if Magazine.objects.filter(prodc_magt_no__in = [post.cn1,post.cn2,post.cn3,post.cn4] and mag_no=post.mag_no):
   form.save()
   return redirect('someview')

else:
   return HttpResponse('Dind't exist or match to this magazine no')

return render(request,'cnCreate.html',{'form':form})

我遇到错误“解压的值太多(预期为 2)”或在订单测试中,此查询不起作用。

我的数据库表是:

 ID     WORK_YMD    LINE_NM  MODEL_CODE    MAG_NO             PRODC_MAGT_NO 
        118002  20191015    PBA-21F BN94-14806W A656MAF00001    BR10BN9414806WA656MAE4035
        118003  20191015    PBA-21F BN94-14806W A656MAF00001    BR10BN9414806WA656MAE4027
        118004  20191015    PBA-21F BN94-14806W A656MAF00001    BR10BN9414806WA656MAE4039
        118005  20191015    PBA-21F BN94-14806W A656MAF00001    BR10BN9414806WA656MAE4037
        118006  20191015    PBA-21F BN94-14806W A656MAF00001    BR10BN9414806WA656MAE4038

如何执行此查询以检查这些 Cns 是否存在于数据库的 prodc_magt_no 字段中

杂志必须相同:post.mag_no = mag_no

标签: pythondjango

解决方案


您不要在过滤器功能中使用“和”。

if Magazine.objects.filter(prodc_magt_no__in=[post.cn1,post.cn2,post.cn3,post.cn4], mag_no=post.mag_no):
    ...do something...

推荐阅读