DRF - 按DateField过滤列表

时间:2015-09-18 15:08:06

标签: python date filter django-rest-framework django-filter

我有一个 Ride 模型:

class Ride(models.Model):
    driver = models.ForeignKey('auth.User', related_name='rides_as_driver')
    destination=models.ForeignKey(Destination, related_name='rides_as_final_destination')
    leaving_time=models.TimeField()
    leaving_date=models.DateField(default=datetime.date.today)
    num_of_spots=models.IntegerField()
    passengers=models.ManyToManyField('auth.User', related_name="rides_as_passenger")
    mid_destinations=models.ManyToManyField(Destination, related_name='rides_as_middle_destination')

我想在今天的日期过滤rides_as_driver字段:

def get(self, request):
        user=self.request.user
        driverRides = user.rides_as_driver.filter(leaving_time=datetime.date.today)

过滤器行引发异常,说:

RemovedInDjango19Warning: Passing callable arguments to queryset is deprecated.
  value, lookups, used_joins = self.prepare_lookup_value(value, lookups, can_reuse, allow_joins)

我也试过获取driverRides = user.rides_as_driver.get(leaving_time=datetime.date.today),但没有效果。

如何按字段值过滤对象列表?

谢谢!

1 个答案:

答案 0 :(得分:1)

首先,leaving_timeTimeField,它存储datetime.time值,而您尝试按datetime.datetime对象进行过滤。您的代码中有leaving_date,您应该明显过滤它。

其次,错误表示您正在传递一个函数(datetime.date.today)作为过滤器参数和this is dropped in Django 1.9

所以你想要做的是:

driverRides = user.rides_as_driver.get(leaving_date=datetime.datetime.now().date())

如果您需要处理应用程序中多个时区的用户,请查看documentation on Time zones