简体   繁体   中英

Multiple field text search in Django

I have an app "api", and a folder "models" in it. In that folder I have several ".py" files, such as "client.py", "therapist.py", "user.py" and etc. In "therapist.py" I have several classes, but I need just one class "TherapistProfile". In that class there are several fields, but I need just "name", "surname", "skills", "city" for searching. So the purpose is to search by writing a sentence. Example (of what user can write in the search bar):

"Tommy davidson listening london" (and it has to be case insensitive ).

The words will be separated by space . Also it has to work if we miss any of the fields :

"Tommy listening london" (we didn't write the surname)

Also:

"London listening tommy" (we are able to change the places of the words )

And not necessarily that the field data consists just 1 word. It can be more. Ex.: "skills": "careful listening" or "city":"Los Angeles"

Here is TherapistProfile class from models/therapist.py:

class TherapistProfile(NonAdminProfile):
  user = models.OneToOneField(Therapist, on_delete=models.CASCADE, related_name='therapist_profile')
  skills = models.ManyToManyField(TherapistSkill, blank=True)
  city = models.ManyToManyField(TherapistCity, blank=True)
  ...

PS The "name" and "surname" fields are in Therapist class (which inherits them from user.py). In TherapistProfile the field is written as "user".

I kinda know the logic: I need to split the sentence into words by space and search each word in each field of each object (if you have a better idea to solve, tell me, please), but I don't know how to code it and where (I mean what to write in views/therapist.py, in models/therapist.py (if it is needed), in TherapistProfile or in TherapistManager). Yes, I don't have view.py file either, I have "views" folder and ".py" files in it (one of them is "therapist.py". And the same thing happens with serializers). And do I need a new serializer for searching?

The answer is:

import from rest_framework import filters
...
...
class TherapistProfileListAPIView(generics.ListAPIView):
    permission_classes = [IsAuthenticated]
    search_fields = ['user__last_name', 'user__first_name', 'skills__title', 'city']
    filter_backends = (filters.SearchFilter,)
    queryset = TherapistProfile.objects.all()
    serializer_class = TherapistProfileSerializer 

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM