2

我将如何创建一个经理,它将返回模型中具有今天日期的所有条目,模型字段是日期时间字段,而不是日期字段?

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 个对象,应该有。

打印 Entries.allowed_entries.all() >>>> []

4

3 回答 3

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)
于 2013-07-05T10:36:21.377 回答
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))
于 2013-07-05T10:40:11.523 回答
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()
于 2014-04-09T15:32:14.480 回答