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

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

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

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


当前回答

你可以使用"__range" 例如:

from datetime import datetime
start_date=datetime(2009, 12, 30)
end_date=datetime(2020,12,30)
Sample.objects.filter(date__range=[start_date,end_date])

其他回答

你可以使用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

Use

Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"])

或者如果你只是想按月份过滤:

Sample.objects.filter(date__year='2011', 
                      date__month='01')

Edit

正如Bernhard Vallant所说,如果你想要一个排除指定范围结束的查询集,你应该考虑他的解决方案,它使用gt/lt(大于/小于)。

很简单,

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