0

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

4

2 回答 2

1

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)
于 2020-08-24T12:28:47.923 回答
1

这是因为如果您的条件都不为真,那么该行将security = Securities.objects.get(pk=symbol)引发错误,因为您没有定义Securities变量并且您的 Pycharm 会向您发出警告。如果您确定每次至少有一个条件会检查您可以通过执行以下操作来消除此警告:

@login_required
    def change_position(request, ptf, symbol):
        Securities = None
        if ptf == 'aht':
            Securities = SecuritiesAHT
        if ptf == 'svr':
            Securities = SecuritiesSVR
        security = Securities.objects.get(pk=symbol)

或者您可以设置另一个默认值,例如:

@login_required
    def change_position(request, ptf, symbol):
        Securities = SecuritiesAHT
        if ptf == 'aht':
            Securities = SecuritiesAHT
        if ptf == 'svr':
            Securities = SecuritiesSVR
        security = Securities.objects.get(pk=symbol)
       ...
于 2020-08-24T12:32:16.130 回答