为了账号安全,请及时绑定邮箱和手机立即绑定

将参数注入原始查询 python

将参数注入原始查询 python

慕桂英4014372 2021-10-19 10:19:42
使用 (where user_id=1) 时,我可以获得结果,但是当注入参数时,我得到了这样的回溯:“用户”对象不可迭代,任何将参数注入原始查询的想法,我的意见.py: class TransactionViews(viewsets.ViewSet):            def list(self, request):                user = get_object_or_404(User, pk=request.user.id)                queryset = Transaction.objects.raw("SELECT product.name, transaction.* from product inner join variant on product.id = variant.product_id inner join transactions_variants on variant.id = transactions_variants.variant_id inner join transaction on transactions_variants.transaction_id = transaction.id where user_id=%s",user)                serializer = TransactionSerializer(queryset, many=True)                return Response(serializer.data, status=200)还有一个问题:queryset = Transaction.objects.filter(user_id=user).exclude(deleted_at__isnull=False)我如何将此“.exclude(deleted_at__isnull=False)”转换为我的原始查询(此排除是软删除的条件)Traceback:File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner  34.             response = get_response(request)File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response  126.                 response = self.process_exception_by_middleware(e, request)File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view  54.         return view_func(*args, **kwargs)File "/usr/local/lib/python3.7/site-packages/rest_framework/viewsets.py" in view  116.             return self.dispatch(request, *args, **kwargs)File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in dispatch  495.             response = self.handle_exception(exc)File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception  455.             self.raise_uncaught_exception(exc)
查看完整描述

2 回答

?
ibeautiful

TA贡献1993条经验 获得超5个赞

正如清楚明确地记录的那样,您需要将查询参数作为元组或列表传递 - 即使只有一个参数。IOW,你想要:

queryset = Transaction.objects.raw("your long query here where user_id=%s", [user])


查看完整回答
反对 回复 2021-10-19
  • 2 回答
  • 0 关注
  • 136 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信