Please help 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 a queryset, but the 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` 

We need to find an adequate solution to this problem. Any ideas? I would be grateful for any help.

  • Corrected. Thank you - Alex Ivanchik
  • Please show me the get_chat_name method itself - Max
  • I think this method does not matter as it only substitutes certain data depending on the type of chat. Added to the main text of the question - Alex Ivanchik
  • Knowing what you are doing inside this method, you can come up with a good alternative to solve your problem. - Max
  • I understand you. I also think about it. I think this topic will be useful to many. If you have any ideas, I'll be glad to hear them out. - Alex Ivanchik

1 answer 1

Here standard filtering will not help you, you will have to write your own. In APIView there is a query_params property, which contains all the parameters of a GET request (post did not try, maybe also). 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)) 
  • And what if you change the name of the chat at the level of not a serializer, but a model? - Alex Ivanchik
  • @AlexIvanchik your search is at DB level, so there is no difference in the serializer to generate the name of the chat or in the model - FeroxTL