year/month/day/hour/minute/second django-rest-framework 中的过滤器

year/month/day/hour/minute/second filters in django-rest-framework

我定义了一个像这样的 django-rest 过滤器:

created_date = django_filters.DateTimeFilter(
    lookup_type=["year", "month", "day", "hour", "minute", "second", "lt", "lte", "gt", "gte"])

这个 url 做了一个正确的查询:created_date < 2015-05-01:

http://localhost:8000/path/objects/?created_date__lt=2015-05-01

gt 同样适用于:created_date > 2015-05-01:

http://localhost:8000/path/objects/?created_date__gt=2015-05-01

这个 url 进行了正确的查询:created_date > 2015-05-01

但是,当我尝试查询年份时:

http://localhost:8000/path/objects/?created_date__year=2015

我明白了

TypeError: int() argument must be a string or a number, not 'datetime.datetime'

我也试过了

http://localhost:8000/path/objects/?created_date__year=2015-05-01

我得到了同样的错误。知道如何让 year/month/day/hour/minute/second 过滤器工作吗?

DateTimeFilter 过滤器将输入值转换为日期时间,因此 created_date__year 与日期时间进行比较,这是错误的。不得不和int.

比较

解决方案 1:

为同一字段添加另一个过滤器:

created_date_part = django_filters.NumberFilter(
    name='created_date',
    lookup_type=["year", "month", "day", "hour", "minute", "second"])

但是您需要为此字段创建另一个名称。

解决方案 2:

编写将继承 CharFilter 并自行完成所有验证的自定义过滤器。