Django 1.10 – Cannot resolve keyword '__' into field. Join on '__' not permitted

Question:

I am trying to make a chart using chartjs for showing all statistics of a poll votes. This is for a specific year with 12 months.

For example,

Are you a programmer?

  1. Yes

  2. No

I would like to show in chart – how many votes users give to 12 months of a year. I ll draw 2 lines in chart that represents Yes and No answers statistics with levels Jauary - December.

I already made all models and they work perfectly.

But when in poll detail page I try to get 12 months statistics of vote record, get an error. Here is view code to get record counts –

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

Here pub_date is the Vote model publish date –

pub_date = models.DateTimeField(auto_now_add=True)

Error is –

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

Thanks for your help!

Asked By: user3384985

||

Answers:

As pointed in comments, if you only need to count something, you don’t have to use values_list.

And the reason you get this error is because when you use double underscore in values_list, django treats it like a foreign key, attempts to make a join and fails. In order to get years as a list, you should write your code as follows:

vote_records = Vote.objects.filter(question = question_record, 
                                   pub_date__year = current_year).values_list('pub_date')
vote_records = [x.year for x in vote_records]

You can generate query as follows:

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)]

We can count Month’s as follows:

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}
Answered By: Prafull kadam
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.