Konstantin Skokov
Konstantin Skokov

Reputation: 157

Django rest filter data by field

Controller:

class TicketMessageSerializerView(generics.RetrieveAPIView):
    queryset = TicketMessage.objects.all()
    serializer_class = TicketMessageSerializer

How to filter the list of messages by the ticket_id field, the value of which is taken from the url:

path('api/tickets/<int:ticket_id>/messages/',
      views.TicketMessageSerializerView.as_view()),

Upvotes: 1

Views: 204

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477598

In that case you work with a ListAPIView (since you return a list of objects), and you can override the get_queryset method to specify what TicketMessages that should be returned, so:

class TicketMessageSerializerView(generics.ListAPIView):
    queryset = TicketMessage.objects.all()
    serializer_class = TicketMessageSerializer

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            ticket_id=self.kwargs['ticket_id']
        )

Upvotes: 1

Related Questions