gadss
gadss

Reputation: 22489

how to get the datetime.date() value from django model?

I have a problem in getting the datetime.date() value in my django... when i trying to get it like this :

>>> s = Booking.objects.values('date_select').distinct('date_select').filter(date_select='2011-12-1')
>>> print s
[{'date_select': datetime.date(2011, 12, 1)}]

it has the column of date_select, i just only want the datetime.date(2011, 12, 1), do anyone have an idea about it? i also try this one but its not working :

>>> s = Booking.objects.values('date_select').distinct('date_select').filter(date_select='2011-12-1')['date_select']
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 153, in __getitem__
    raise TypeError
TypeError
>>> 

thanks...

Upvotes: 1

Views: 750

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Dimitry's answer works but it will raise an exception if your query does not return any results at all (because the index will not exist, likely resulting in IndexError exception).

This does the same, but will not error if the query returns empty results:

s = Booking.objects.values('date_select').distinct('date_select').filter(date_select='2011-12-1')
if s.count():
    s = s.get()['date_select']

Also worth mentioning that if your query returns more than one result, you'll have to adjust the code accordingly.

Upvotes: 0

dMb
dMb

Reputation: 9337

you are getting back a list with one element so you need to do this:

s = Booking.objects.values('date_select').distinct('date_select').filter(date_select='2011-12-1')[0]['date_select']

Upvotes: 1

Related Questions