1

I am using Django Rest Framework.

In the queryset I'm trying to filter my objects based on IF their Date is greater than or equal to today. Like so:

class DateViewSet(viewsets.ModelViewSet):
    """
    API Endpoint to retrieve all dates after today.
    """
    serializer_class = DateSerializer
    today = datetime.date.today()
    queryset = EventDate.objects.filter(end_date__gte=today)

But this ends up showing the past dates as well.

my serializer:

class DateSerializer(serializers.ModelSerializer):
    class Meta:
        model = EventDate
        fields = ('start_date', 'end_date')

And then I pass it on to the Event Serializer:

class EventSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.StringRelatedField()
    dates = DateSerializer(many=True, read_only=True)

    class Meta:
        model = Event
        fields = '__all__'
        extra_kwargs = {
            'url': {'lookup_field': 'slug'},
        }

My goal is when my API returns all events it should not return all dates that have been in the past.

What am I doing wrong?

Tony
  • 2,382
  • 7
  • 32
  • 51

1 Answers1

4

The problem is that today = datetime.date.today() will be evaluated when you construct the class, not each time when you need to fetch these attributes.

You can override the get_queryset method to fetch make a query with the date when the request is made:

from django.utils.timezone import now

class DateViewSet(viewsets.ModelViewSet):
    """
    API Endpoint to retrieve all dates after today.
    """
    serializer_class = DateSerializer

    def get_queryset(self, *args, **kwargs):
        EventDate.objects.filter(end_date__gte=now().date())
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Great answer explaination. – Mirza715 Mar 09 '20 at 02:10
  • Hey Willem, Thanks for your reply! The problem I have now is that the queryset does not affect the values in the EventSerializer (dates = DateSerializer). My goal is to filter and pass the dates to the EventSerializer – Tony Mar 09 '20 at 11:37
  • @TonyKyriakidis: but then you need an `EventViewSet` I think? You can filter with `Event.objects.filter(eventdate__end_date__gte=now().date())` (where `eventdate` is the `ForeignKey` from `Event` to `EventDate`, this might be a different name). – Willem Van Onsem Mar 09 '20 at 11:40