操作错误(1054,"未知列'月'在'字段列表'")

时间:2017-02-11 21:23:46

标签: python mysql django

我从我的数据库中每月注释价格,我正面临这个错误,我试图找出原因,所以在我的模型中我有DateTimeField,我试过在shell里面玩数据,一切都很好,我有它,我也试着用MySQL Workbench查看数据库,数据在那里,Full traceback和其他代码,有人可以解释什么是我的注释错了吗?

models.py

created = models.DateTimeField(auto_now_add=True)

views.py

from django.views.generic import ListView
from django.db.models import Count, Sum
from django.db import connection

from projects.models import Project
from .services import CurrencyConversionService



class ProjectStatisticsList(ListView):
    model = Project
    template_name = 'statistics/statistics_list.html'
    paginate_by = 10

    def get_context_data(self, **kwargs):
        context = super(ProjectStatisticsList, self).get_context_data(**kwargs)

        truncate_month = connection.ops.date_trunc_sql("year", "month")
        total_price_per_month = Project.objects.extra({"month": truncate_month}).values("month").annotate(sum_price=Sum("price_aux"))

        context['total_price_per_month'] = total_price_per_month
        return context

在模板中:

<tr>
    {% for data in total_price_per_month %}
   <th class="aligh-left"> </th>
    {% endfor %}
   <td>Month: {{ data.month }}</td>
    <td>Price: {{ data.sum_price }}</td>
  </tr>

1 个答案:

答案 0 :(得分:0)

我认为您不能在extra条款中使用values中的字段。

但实际上这是错误的做法。您应该使用Django的数据库功能支持;具体来说,extract function

from django.db.models.functions import Extract
Project.objects.annotate(month=Extract('created', 'month').values("month").annotate(sum_price=Sum("price_aux"))