Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过post变量的Django queryset过滤器_Python_Django_Django Queryset - Fatal编程技术网

Python 通过post变量的Django queryset过滤器

Python 通过post变量的Django queryset过滤器,python,django,django-queryset,Python,Django,Django Queryset,我正在尝试使用Django做一个queryset过滤器。我有优惠券对象,带有code,这是一个CharField。我想找到所有优惠券对象与匹配的代码 我的模型: class Coupon(models.Model): code = models.CharField(max_length=50) ... other fields 我的看法是: # This method returns the queryset Coupon.objects.filter(code = "abc1

我正在尝试使用Django做一个queryset过滤器。我有
优惠券
对象,带有
code
,这是一个
CharField
。我想找到所有
优惠券
对象与匹配的
代码

我的模型:

class Coupon(models.Model):
    code = models.CharField(max_length=50)
    ... other fields
我的看法是:

# This method returns the queryset
Coupon.objects.filter(code = "abc123")

# This part of the code is not working the way I want to
couponCode = str(request.POST.get("code"))
Coupon.objects.filter(code = couponCode)
我已确保POST变量为“abc123”,但在第二次查询中仍然得到一个空查询集。

删除
str()
部分。仅将其保留为:

couponCode=request.POST.get(“code”)
, 然后你可以做:

优惠券.objects.filter(code=couponCode)

希望这有帮助。

只要使用

couponCode = request.POST['code']
而不是

couponCode = str(request.POST.get("code"))

添加
assert-couponCode=='abc123'
您是否打印了
couponCode
并检查了值,或者如上所述,执行
assert
checkDo请记住,如果找不到键,使用request.POST['code']将引发异常。更安全的选项是request.POST.get(“code”),因为如果找不到密钥,它只会返回None。