Please help to solve the problem. I need to organize a search by chat name. But the chat name is created when the object is serialized.
name = serializers.SerializerMethodField('get_chat_name')
"SearchFilter" works with queryset, but queryset does not have this field. Because this field is added at the time of serialization.
class ChatList(generics.ListAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = ChatSerializers filter_backends = (SearchFilter,) search_fields = ('name',) def get_queryset(self): user = self.request.user return Chat.objects.filter(chatusers__user=user) class ChatSerializers(serializers.ModelSerializer): name = serializers.SerializerMethodField('get_chat_name') def get_chat_name(self, chat): if chat.type == 0: queryset = ChatUsers.objects.exclude(user = self.context['request'].user).get(chat=chat.pk) user_name = queryset.user.get_full_name() if user_name: return user_name else: return queryset.user.username if chat.type == 1: return chat.name`
It is necessary to find an adequate solution to this problem. Any ideas? I would be grateful for any help.
Standard filtering won't help you here, you have to write your own.
APIView has a
query_params property that contains all the parameters of a
GET request (post did not try, maybe too). In general, everything is described in the documentation , you need to override the
get_queryset method and filter the results you need something like this:
qs = Chat.objects.all() query = self.query_params.get('q') if query: qs = qs.filter(Q(chat__type=1) | Q(chat__name__like=query), Q(chat__type=0) | Q(chat__user__first_name__like=query))