python - Django:在视图中引用模型——>局部变量可能在赋值之前被引用
问题描述
我有一个小型 Django 应用程序,我想管理两个股票投资组合。我创建了两个具有相同结构(基于抽象模型)的表(SecuritiesSVR 和 SecuritiesAHT)。在网址中,我添加了一个参数“ptf”:portfolio/str:ptf/change_position
现在我想通过如下视图访问这两个表:
@login_required
def change_position(request, ptf, symbol):
if ptf == 'aht':
Securities = SecuritiesAHT
if ptf == 'svr':
Securities = SecuritiesSVR
security = Securities.objects.get(pk=symbol)
...
在 PyCharm 中,我的变量 Securities 收到警告:“局部变量可能在分配之前被引用”。但是,该视图似乎工作正常。有谁知道我为什么收到此警告?
解决方案
You see this warning because in case when ptf
variable's value is not 'aht'
and not 'svr
code blocks in both if statements will not be triggered and Security
variable will not be defined. To remove this warning, you can add additional block to return error response.
@login_required
def change_position(request, ptf, symbol):
if ptf == 'aht':
Securities = SecuritiesAHT
elif ptf == 'svr':
Securities = SecuritiesSVR
else:
return HttpResponseBadRequest('not valid ptf')
security = Securities.objects.get(pk=symbol)
推荐阅读
- jwt - 如何通过 Cookie 撤销 JWT 身份验证?
- scala - Spark 中的循环分区如何工作?
- reactjs - 在 React Bootstrap 对话框中,如果对话框的主体内部有一个组件,如何引用组件及其状态?
- python - try-except 后“else”块的目的是什么?
- wordpress - Apache 子域重定向到 www 上的 WordPress
- javascript - 如何在 Facebook 等我的项目中创建和表情符号?
- python - 使用 python 读取 MYSQL Db 会返回一个元组,我需要将其转换为列表
- code-signing-certificate - 代码签名证书过期后,已经安装的应用程序会发生什么?
- arrays - 在非常大的数组中计算较小或相等元素的更快方法?
- c# - 如何在 C# 中像存储过程一样执行 Access 查询