Django:进行数据库查询时的UnboundLocalError

时间:2012-12-17 12:36:25

标签: python django python-2.7 matplotlib django-views

我正在尝试在django上做一个matplotlib条形图。将使用的数据将从我的数据库中查询。

我运行代码时遇到了这个错误:

  

引用了/graph.png局部变量'topic'的UnboundLocalError   在分配之前

matplotlib部分的代码都是正确的,因为我之前尝试运行静态数据并且它有效。但是,当我尝试从数据库中查询数据时,会在views.py上导致此错误。我之前在不同的页面上多次完成此查询并且工作正常。但它不适用于此请求。为什么呢?

def bar_chart(request):
    #Topic Distribution
    topics = list(topic.objects.filter(subject_id=subj_id).order_by('id').values())

    fig = Figure()
    ax = fig.add_subplot(111)

    N = 5
    ind = np.arange(N)
    width = 0.35

    group_labels = [] #list of x-axis tick labels
    y = [] #list of y-values
    total_marks = 0 #total marks
    for topic in topics:
        t_questions = question.objects.filter(topic_id=topic.id)
        if (len(t_questions) != 0):
            topic_marks = 0 #each topic starts at 0 marks distribution
            for t_question in topic_questions:
                topic_marks += t_question.marks #accumulate the marks
            total_marks += topic_marks
            y.append(topic_marks)
            group_labels.append(topic.title)
    for yval in y:
        yval = yval/total_marks * 100 #convert to percentage


    ax.bar(ind, y, width, color='r')
    ax.set_ylabel('Distribution in %')
    ax.set_title('Topic Distribution')
    ax.set_xticks(ind)
    ax.set_xticklabels(group_labels)
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    response=HttpResponse(content_type='image/png')
    canvas.print_png(response)

    return response

1 个答案:

答案 0 :(得分:3)

错误在于:

topics = list(topic.objects.filter(subject_id=subj_id).order_by('id').values())

<击> 如果您遵循模型的通用命名约定,您的可能称为Topic,因此它应该是

topics = list(Topic.objects.filter(subject_id=subj_id).order_by('id').values())

否则您可能错过了导入。

它是由函数中定义的局部变量主题引起的,并且掩盖了全局变量主题。