django:赋值前引用的局部变量

时间:2014-04-23 09:32:19

标签: django

我想做一个简单的查询,但它会引发异常。

查看:

from callidus_app.models import department
...
def select_department(request):
    context = RequestContext(request)
    department_list = department.objects.all() #local variable 'department' referenced before assignment

    context_dict = {'departments': department_list}
    for department in department_list:
        department.url=department.departmentName.replace(' ','_')

    return render_to_response('callidus_app/select_department.html', context_dict,context)

部门模特:

class department(models.Model):
    departmentName = models.CharField(max_length = 20)
    leaders = models.CharField(max_length = 20)
    logoPath = models.CharField(max_length = 150)
    def __str__(self):
        return self.departmentName

1 个答案:

答案 0 :(得分:0)

你有两个名为department的东西:你的模型,以及迭代department_list时的循环变量。在函数内的任何位置分配名称会使其成为局部变量,因此会出错。

快速修复是在循环中使用不同的变量名,但实际上你应该重命名你的模型:接受的样式是使用InitialCaps作为类名,包括模型,所以它应该是Department。