python - Django:进行数据库查询时出现UnboundLocalError

标签 python django python-2.7 matplotlib django-views

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

我在运行代码时遇到此错误:

UnboundLocalError at /graph.png local variable 'topic' referenced before assignment

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

最佳答案

错误在这里:

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

<罢工> 如果您遵循模型的常见命名约定,您的模型可能称为主题,因此应该是

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

否则您可能会错过导入。

这是由于函数内定义的局部变量 topic 覆盖了全局变量 topic 造成的。

关于python - Django:进行数据库查询时出现UnboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13914301/

相关文章:

python - 使用 Tkinter 集成图片

python 基于标准的计数示例

django - 控制 Django auth 用户对特定对象实例的访问

django-registration 没有名为 simple 的模块

mysql - Django,长过滤器查询

python - 定义类 : How to inheriting from object class

python-2.7 - 使用 tweepy 向最新关注者发送直接消息

python - python 中的 Cron 解析器和验证

python - 解析带有法语月份缩写的日期

Python - 评估列表子集的元素