Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top