Sandip Agarwal
Sandip Agarwal

Reputation: 1910

Retrieving only the date part of a datetime column in Django

I am a starter in Django/Python.

I have a model MyModel. It has many fields of datetime, char, integer types. Now, I want a values list which has values of the datetime fields containing only the date parts.

I have tried using the dates function [reference] (https://docs.djangoproject.com/en/1.2/ref/models/querysets/#dates), but it works only with one field. I have multiple datetime fields and all have to be retrieved in the required format.

Basically, I want a Django equivalent of :

select stringfield1, date(datefield1), integerfield1, date(datefield2) from mymodel; (PostGreSQL)

Is this even possible? If it is, how should I proceed further?

Upvotes: 1

Views: 1309

Answers (1)

Ismail Badawi
Ismail Badawi

Reputation: 37177

I'm not sure if Django has a builtin way of doing this. You could use itertools.imap to lazily convert the fields in question into date objects:

from itertools import imap
values = MyModel.objects.values_list('stringfield1', 'datefield1', 
                                       'integerfield1', 'datefield2')
values = imap(lambda (s, d1, i, d2): (s, d1.date(), i, d2.date()), values) 

(But note that after this you're not dealing with a ValuesListQuerySet anymore but with an itertools.imap object.)

Upvotes: 1

Related Questions