Django经理返回今天的所有条目 - DateTimeField

时间:2013-07-05 10:13:36

标签: python django datetime django-managers

如何让管理员返回今天日期的模型中的所有条目,模型字段是日期时间字段,而不是日期字段?

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

这是我尝试过的,但它返回0个对象,应该有。

  

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

3 个答案:

答案 0 :(得分:2)

您可以尝试将这两个日期设置为午夜:

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)

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

不需要经理来完成这么简单的任务。

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

然后只是:

>>> Entry.get_for_today()