我在一个模型中有一个字段:

class Sample(models.Model):
    date = fields.DateField(auto_now=False)

现在,我需要按日期范围筛选对象。

如何过滤日期在1- january -2011和31- january -2011之间的所有对象?


当前回答

为了使它更灵活,你可以这样设计一个FilterBackend:

class AnalyticsFilterBackend(generic_filters.BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        predicate = request.query_params # or request.data for POST

        if predicate.get('from_date', None) is not None and predicate.get('to_date', None) is not None:
            queryset = queryset.filter(your_date__range=(predicate['from_date'], predicate['to_date']))

        if predicate.get('from_date', None) is not None and predicate.get('to_date', None) is None:
            queryset = queryset.filter(your_date__gte=predicate['from_date'])

        if predicate.get('to_date', None) is not None and predicate.get('from_date', None) is None:
            queryset = queryset.filter(your_date__lte=predicate['to_date'])
        return queryset

其他回答

您可以通过使用datetime来避免由于DateTimeField/date对象比较中缺乏精度而导致的“阻抗不匹配”(如果使用range就会出现这种情况)。Timedelta用于在范围内的最后日期后添加一天。这是这样的:

start = date(2012, 12, 11)
end = date(2012, 12, 18)
new_end = end + datetime.timedelta(days=1)

ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])

如前所述,如果不这样做,最后一天的记录将被忽略。

编辑以避免使用datetime.combine——在与DateTimeField进行比较时,坚持使用date实例似乎更合乎逻辑,而不是使用丢弃(并令人困惑)的datetime对象。详见下面的评论。

很简单,

YourModel.objects.filter(YOUR_DATE_FIELD__date=timezone.now())

对我有用

为了使它更灵活,你可以这样设计一个FilterBackend:

class AnalyticsFilterBackend(generic_filters.BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        predicate = request.query_params # or request.data for POST

        if predicate.get('from_date', None) is not None and predicate.get('to_date', None) is not None:
            queryset = queryset.filter(your_date__range=(predicate['from_date'], predicate['to_date']))

        if predicate.get('from_date', None) is not None and predicate.get('to_date', None) is None:
            queryset = queryset.filter(your_date__gte=predicate['from_date'])

        if predicate.get('to_date', None) is not None and predicate.get('from_date', None) is None:
            queryset = queryset.filter(your_date__lte=predicate['to_date'])
        return queryset

你可以使用django的datetime过滤器。日期对象:

import datetime
samples = Sample.objects.filter(sampledate__gte=datetime.date(2011, 1, 1),
                                sampledate__lte=datetime.date(2011, 1, 31))

模型

date = models.DateField()

View

def get_queryset(self):  

    fromDate = self.request.query_params.get('fromDate',None)
    toDate = self.request.query_params.get('toDate',None)
    response  = yourModel.objects.filter(date__gte=fromDate,date__lte=toDate)
    return response