如何在Django中基于Datefield过滤查询集?

时间:2019-01-12 21:08:07

标签: python django django-queryset

我需要根据今天/明天的日期来过滤查询集 并且可用字段是日期字段而不是日期时间字段

我正在使用自定义管理器来提供过滤结果

class CallbackReqManager(models.Manager):
def get_queryset(self):
    return super().get_queryset().filter()

def callbacktoday(self):
    today=date.today

    print(today)
    return self.filter(prefereddate=today)


class CallbackReq(models.Model):

    name    =   models.CharField(max_length=50)
    email   =   models.EmailField(max_length=254)
    query   =   models.CharField(max_length=150)
    preferedtime = models.TimeField(auto_now=False, auto_now_add=False)
    prefereddate = models.DateField(auto_now=False, auto_now_add=False)
    requestedon  = models.DateTimeField(auto_now_add=True)
    attended  =   models.BooleanField(default=False)  #   whether call back is met

    objects =   CallbackReqManager()

但是我得到

TypeError:  match = date_re.match(value)

TypeError: expected string or bytes-like object

2 个答案:

答案 0 :(得分:1)

您可能想这样写

today = date.today()

让我知道是否仍然出现某些错误。

答案 1 :(得分:1)

您可以将新的经理添加到模型中,一个可以通过今天的日期进行过滤,另一个可以通过明天的数据进行过滤。这是一个例子

from datetime import date, timedalte
from django import models

class FilterByToday(models.Manager):
def get_queryset(self):
    """Filtering by today's date"""
    return super().get_queryset().filter(
        prefereddate=date.today()
    )

class FilterByTomorrow(models.Manager):
    """
    filtering by tomorrow's date
    where: date.today() + timedelta(days=1)
    is: Today + 1 day
    """
    def get_queryset(self):
        return super().get_queryset().filter(
            prefereddate=date.today() + timedalte(days=1)
        )


class CallbackReq(models.Model):

    name    =   models.CharField(max_length=50)
    email   =   models.EmailField(max_length=254)
    query   =   models.CharField(max_length=150)
    preferedtime = models.TimeField(auto_now=False, auto_now_add=False)
    prefereddate = models.DateField(auto_now=False, auto_now_add=False)
    requestedon  = models.DateTimeField(auto_now_add=True)
    attended  =   models.BooleanField(default=False)  #   whether call back is met
    # You can keep your default objects manager
    objects =   models.Manager()
    # Today's manager
    objects_today = FilterByToday()
    # Tomorrow's manager
    objects_tomorrow = FilterByTomorrow()

因此,在您的下一个代码中,您可以使用,例如:

# Return all the Model's records without using the custom managers
instance = CallbackReq.objects.all()
# Return all Model's records by filtering them by today's date
instance = CallbackReq.objects_today.all()
# Return all Model's records by filtering them by tomorrow's date
instance = CallbackReq.objects_tomorrow.all()

有关更多信息,请访问official documentation