0

Is it possible to order/sort a serializer availability that is both a reverse lookup and nested inside unit serializer? For example, I wish to order availability by start_time instead of id.

Below is what I tried but I get .order_by('-start_time')' ^ SyntaxError: invalid syntax

Serializers

class AvailabilitySerializer(serializers.ModelSerializer):
    staff = StaffSerializer() 

    class Meta:
        model = Availability
        fields = ['id','start_time', 'end_time','staff']

class ManagerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Manager
        fields = ['company', 'logo']

class UnitSerializer(serializers.ModelSerializer):
    availability = AvailabilitySerializer(source='availability_set.order_by('-start_time')', many=True)
    manager = ManagerSerializer()


    class Meta:
        model = Unit
        fields = ['id', 'address', 'manager', 'availability']
1
  • in your Availability model just try to add ordering = ('-start_time') Commented Jan 9, 2020 at 4:57

1 Answer 1

2

You can override the field and provide the serializer with your own queryset and then return the data:

from rest_framework.serializers import SerializerMethodField


class UnitSerializer(serializers.ModelSerializer):
    availability = SerializerMethodField()
    manager = ManagerSerializer()

    class Meta:
        model = Unit
        fields = ['id', 'address', 'manager', 'availability']

    def get_availability(self, instance):
        queryset = instance.availability_set.order_by('-start_time')
        return AvailabilitySerializer(queryset, many=True).data

SerializerMethodField

Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I was trying to accomplish! Thank you very much :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.