Home > Mobile >  How to implement date range filter in django-filters
How to implement date range filter in django-filters

Time:05-24

I want to filter upload_date in date range (upload_date__lte, upload_date__gte) My models is

class MetaData(models.Model):
    # Video Info
    tag = models.CharField(max_length=100, default="")
    category = models.CharField(max_length=100, default="")
    upload_date = models.DateField()
    upload_time = models.TimeField()
    caption = models.CharField(max_length=2000, blank=True, default='Not Set')
    comments = models.IntegerField()
    likes = models.IntegerField()
    shourtcode = models.CharField(max_length=200, default='', unique=True)
    owner_id = models.PositiveIntegerField(default=0)
    # Post
    link = models.URLField(unique=True)
    user = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, blank=True)
    status = models.CharField(max_length=20, choices=(
        ('Pending', 'Pending'), ('Acquired', 'Acquired'), ('Rejected', 'Rejected'), ('Approved', 'Approved')), default='Pending')
    public = models.BooleanField(default=False)
    date = models.DateTimeField(auto_now_add=True)

My views is

class FetchMetaData(ListCreateAPIView):
    queryset = MetaData.objects.all()
    serializer_class = s.MetaDataSerializer
    name = 'metadata-list'
    pagination_class = DefaultPagePagination
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]

    filter_fields = (
        "tag",
        "category",
        "public",
        "status",
        "user",
        "upload_date",

    )
    ordering_fields = (
        '-upload_date',
        '-upload_time',
        'likes',
        'comments',
    )
    search_fields = (
        "$tag",
        "$caption",
        "$category"
    )
    ordering = ['-upload_date']

What I want is filter range in upload_date

Like http://localhost/tags/filterMetadata/?upload_date__lte=2022-01-05?upload_date__gte=2022-01-05

CodePudding user response:

I think you need to create MetaDataFilter.

from django_filters import rest_framework as filters

class MetaDataFilter(filters.FilterSet):
    upload_date = filters.DateFromToRangeFilter()

    class Meta:
        model = MetaData
        fields = ['upload_date']

In the view, you can set the filterset_class

class FetchMetaData(ListCreateAPIView):
    ...
    filterset_class = MetaDataFilter

Then, the api url should be .../filterMetadata/?upload_date_before=2022-01-05&upload_date_after=2022-01-05

Hope it could help.

  • Related