My question is whether there is a way to use filters given by the user in the URL to order a queryset using nested serializers using the nested fields.
For example:
class EventsSerializer(serializers.ModelSerializer):
class Meta:
model = Events
fields = ['date', 'location']
class GuestsSerializer(serializers.ModelSerializer):
events = EventsSerializer()
class Meta:
model = Events
fields = ['name', 'phone', 'seat_no', 'events']
class GuestEvents(generics.ListAPIView):
serializer_class = GuestsSerializer
name_param = self.kwargs['name']
order_param = self.request.query_params.get('orderBy')
def get_queryset(self):
data = Guests.objects.select_related('events').filter(name=name_param)
return data
def list(self, request, *args, **kwargs):
res = super(TestData, self).list(request, *args, **kwargs)
res.data = {"guestevents":res.data}
return res
If i have these serializers and view in order to show what events a guest is attending and the ordering is by default ascending based on the date; is it possible to have the user type location as the orderType and have that be used for ordering or can i not make use of thee 'location' field at this point?
CodePudding user response:
DRF has OrderingFilter which can help you:
filter_backends = [filters.OrderingFilter]
ordering_fields = '__all__'
Declare this in your view and specify fields which you want to order by. Then you can do that using ?ordering=name etc.
More info on that: https://www.django-rest-framework.org/api-guide/filtering/#orderingfilter