首页 > 解决方案 > 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 收到警告:“局部变量可能在分配之前被引用”。但是,该视图似乎工作正常。有谁知道我为什么收到此警告?

标签: pythondjango

解决方案


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)

推荐阅读