Question

How would I make a manager that will return all the entries in a model with todays date, the model field is a datetime field, not a datefield?

timestamp = models.DateTimeField(auto_now=True)

class ValidEntryManager(models.Manager):
    def get_query_set(self):
        return super(ValidEntryManager, self).get_query_set().filter(timestamp__gte=datetime.today(), timestamp__lte=datetime.today())

allowed_entries = ValidEntryManager()

This is what I tried, but it returns 0 objects, there should be.

print Entries.allowed_entries.all() >>>> []

Was it helpful?

Solution

You could try setting both dates to midnight:

class ValidEntryManager(models.Manager):
    def get_query_set(self):
        today = datetime.today()
        start_date = datetime(today.year, today.month, today.day)
        end_date = datetime(today.year, today.month, today.day+1)
        return super(ValidEntryManager, self).get_query_set().filter(timestamp__gte=start_date, timestamp__lte=end_date)

OTHER TIPS

Try this

from datetime import datetime, timedelta

class ValidEntryManager(models.Manager):
    def get_query_set(self):
        return super(ValidEntryManager, self).get_query_set().filter(timestamp__range=(datetime.now(), datetime.now()- timedelta(days=1))

No need for a manager for such a simple task.

from datetime import date

...

@staticmethod
def get_for_today():
    today = date.today()
    return Entry.objects.filter(date_time__day=today.day,
                                date_time__month=today.month,
                                date_time__year=today.year,)

And then just:

>>> Entry.get_for_today()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top