0

我需要在用户提供字符串时实现过滤器,并且它应该限制为那些。我尝试使用过滤器后端,但没有任何想法。因为我是新手,所以不知道如何进行。

视图.py

 from rest_framework import generics
    from funder.models.funders import Funder
    from django.contrib.postgres.search import TrigramSimilarity
    from api.serializers.researcher_dashboard.funder import FunderSerializer
    

class FunderViewSet(generics.ListAPIView):
    serializer_class = FunderSerializer
    queryset = Funder.objects.all()
    filter_backends = (filters.DjangoFilterBackend)
    search_field = 'name'
    model = Funder
    limit = 10

    def filter_queryset(self, queryset):
        term = self.kwargs.get('term')
        if term:
            queryset = self.model.objects.annotate(
                similarity=TrigramSimilarity(
                    expression=self.search_field,
                    string=term,
                ).filter(similarity__gt=0.3).order_by('-similarity')) 
          

        if queryset.count() > self.limit:
            return queryset[:self.limit]

        return queryset
4

0 回答 0