繁体   English   中英

检查变量是否是查询集 django 中的列表

[英]Check if varible is an list in 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

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

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

您可以使用 python 的成员身份来检测项目是否在列表中。

if post.mag_no in [post.cn1,post.cn2,post.cn3,post.cn4]:
    form.save()
   return redirect('someview')

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

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

这是不好的语法:

Magazine.objects.filter(prodc_magt_no__in = [post.cn1,post.cn2,post.cn3,post.cn4] and mag_no=post.mag_no)

相反,它应该是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM