Skip to main content
 首页 » 编程设计

python之Django 1.10之无法将关键字 '__' 解析为字段。不允许加入 '__'

2024年08月21日25davidwang456

我正在尝试使用 chartjs 制作图表用于显示民意调查投票的所有统计数据。这是针对有 12 个月的特定年份。

例如,

你是程序员吗?

  1. 是

  2. 没有

我想在图表中显示 - 用户给一年中的 12 个月投了多少票。我将在图表中绘制 2 条线,分别代表 Yes 和 No 答案统计数据,级别为 Jauary - December。

我已经制作了所有模型并且它们运行良好。

但是当我在poll 详细信息页面中尝试获取 12 个月的投票记录统计信息时,出现错误。这是获取记录数的查看代码 -

vote_records = Vote.objects.filter(question = question_record, pub_date__year = current_year).values_list('pub_date__month').count() 

这里的pub_date是Vote模型发布日期-

pub_date = models.DateTimeField(auto_now_add=True) 

错误是-

Cannot resolve keyword 'month' into field. Join on 'pub_date' not permitted.

感谢您的帮助!

请您参考如下方法:

您可以按如下方式生成查询:

vote_records = Vote.objects.filter( 
    question=question_record, pub_date__year=current_year 
).values_list( 
    'pub_date', flat=True 
) 

We are using flat key because

It gives list tuple as given :

[(datetime.datetime(2016, 11, 11, 15, 5, 3, 875344),),]

After using flat = True it is

[(datetime.datetime(2016, 11, 11, 15, 5, 3, 875344)]

我们可以按如下方式计算月份:

dMonthsCount = {} 
 
for i in vote_records: 
    if i.month in d: 
        dMonthsCount[i.month] = dMonthsCount[i.month] + 1 
    else: 
        dMonthsCount[i.month] = 1 
 
#Here key is month number and value is count 
#dMonthsCount = {10: 5, 11: 8, 4: 3} 
 
#We can also convert as follow:  
Months_dict = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 
              8:'August', 9:'September', 10:'October', 11:'November', 12:'December'} 
MonthsCount={} 
for i in dMonthsCount: 
  MonthsCount[Months_dict[i]] = dMonthsCount[i] 
 
#MonthsCount = {'April': 3, 'November': 8, 'October': 5}