5

I'm writing a manager in Django 1.5. I want to return a QuerySet that contains objects with a start date either today or in the future. Based on this answer to a previous problem I presume my manager needs to use a callable rather than a function. I've written:

...
return super(UpcomingEventManager, self).get_query_set().filter(date__gte=timezone.now().date)

I read that code as being a callable (date) that relies on a function (timezone.now()) for its value. But will Django treat it as a callable or a function?

I know I can test this by creating an object and waiting until tomorrow but I'd rather understand this fully.

Community
  • 1
  • 1
cms_mgr
  • 1,977
  • 2
  • 17
  • 31

2 Answers2

11

Django 1.10 get today date:

>>> from django.utils import timezone
>>> timezone.now()
datetime.datetime(2016, 11, 29, 7, 23, 55, 924928, tzinfo=<UTC>)
>>> timezone.now().date
<built-in method date of datetime.datetime object at 0x7f42512b42a0>
>>> timezone.now().date()
datetime.date(2016, 11, 29)
8

You seem to be using callback in a way I don't recognise here.

timezone.now() returns a value of type datetime.datetime. That class has a property, date, which returns the date portion of that value. There are no callbacks involved here at all.

Edit Your confusion is stemming from a mis-reading of the previous question. That's about default values used in model field declarations: as the answers there state, you need to use a callable rather than a value because the declaration is evaluated on first import.

But that's not what you're doing here at all. You're simply passing a value to a function from another function. There's no early evaluation involved: the code will be evaluated when the function is called, so it's perfectly safe to use date() or today() there. In fact, in this case passing the callable rather than the value will not work.

(Also, you should use the word "callable" rather than "callback" here: a callback implies some sort of asynchronous behaviour, which isn't what's happening.)

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 1
    If I understand you correctly then the correct way to do this would be something like `datetime.date.today` then, because that is a callback on the `today` function. Is that right? Also, timezone.now().date returns the date function, not a value. – cms_mgr Mar 26 '14 at 12:45
  • I think I understand now. Thanks for this. I've edited the question to clarify terminology as you suggest. – cms_mgr Mar 26 '14 at 13:02
  • Chances are that if you use setting `USE_TZ = True` and are using `timezone.now().date()`, what you really want is `timezone.localdate()` otherwise you get the date for the UTC timezone. – heyhugo Feb 21 '21 at 11:33