How do I filter query objects by date range in Django?

后端 未结 7 1522
执念已碎
执念已碎 2020-11-22 16:02

I\'ve got a field in one model like:

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

Now, I need to filter the obje

相关标签:
7条回答
  • 2020-11-22 16:47

    To make it more flexible, you can design a FilterBackend as below:

    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
    
    0 讨论(0)
提交回复
热议问题