Sid
Sid

Reputation: 611

Django-MySQL is unable to recognise model.column in queryset extra?

I have SQLite and MySQL installed on my local and development machine respectively. Following is working fine on my local machine(with SQLite):

select_single = {'date': "strftime('%%Y-%%m-%%d',projectName_Modelname.created)"}
queryset.extra(select=select_single)

But since strftime doesn't work with MySQL(link), I tried using DATE_FORMAT() as suggested in given link and other places too. Though now when I execute below:

select_single = {'date': "DATE_FORMAT(projectName_Modelname.created, '%%Y-%%m-%%d')"}
queryset.extra(select=select_single)

Following error comes:

DatabaseError: (1054, "Unknown column 'projectName_Modelname.created' in 'field list'")

where 'created' is Datetime field in Django model 'Modelname' of app 'projectName'

To debug when I replace projectName_Modelname.created with NOW() no error comes. I have also tried just Modelname.created instead of projectName_Modelname.created though with no benefit?

Note: I am using Django1.5.5

Upvotes: 0

Views: 118

Answers (1)

Bharadwaj Srigiriraju
Bharadwaj Srigiriraju

Reputation: 2206

I think it should be something like:

date_raw_query = {'date': "date_format(created, '%%Y-%%m-%%d')"}

and then try

queryset.extra(select=date_raw_query)

Hope that works in your setup. I have tried this on Django 1.7 and MySQL and seems to be working.

Also remember that if SQL errors start coming up, you can always do a print queryset.extra(select=date_raw_query).query to see what might be going wrong.

And when it comes to writing compatible code between SQLite and MySQL like this one, writing a custom MySQL function has been suggested here

But I would suggest otherwise. It's better to have a similar dev environment with MySQL setup in local and also, upgrade Django as soon as possible. :P

Upvotes: 1

Related Questions