Sander Bakker
Sander Bakker

Reputation: 621

DRF - Filter on date instead of date time in URL

I wrote the following code:

class FixtureSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Fixture
        fields = ["home", "away", "league", "round", "date"]

class FixtureViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows fixture to be viewed or edited.
    """
    queryset = Fixture.objects.all().order_by('-date')
    serializer_class = FixtureSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
    filterset_fields = ('date', "home", "away",)

I want to filter on only on the date of a fixture instead of on the date/time combination. I tried it with the following GET requests:

localhost:8000/fixtures?date=2020-05-16
localhost:8000/fixtures?date__date=2020-05-16

I also want the original date to be returned in the response of the request. Any idea on how to do this?

Upvotes: 2

Views: 721

Answers (1)

Astik Anand
Astik Anand

Reputation: 13047

You can filter using date on DateTimeField like below

class FixtureViewSet(viewsets.ModelViewSet):
    serializer_class = FixtureSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
    filterset_fields = ('date', "home", "away",)

    def get_queryset(self):
        given_date = self.request.query_params.get('date')
        queryset = Fixture.objects.filter(date__date=given_date).order_by('date')

        return queryset

Here given_date is parameter passed from url.

Upvotes: 2

Related Questions