使用Django RestFramework和Angular前端构建过滤器

时间:2019-10-28 16:33:48

标签: django angular

我尝试从Django后端为前端的Angular构建过滤器,或者如何使用restframework_filter构建过滤器,请人们帮助,我将其保存在后端

viewset.py

from snippets.models import Snippet
from .serializers import SnippetSerializer
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from django_filters  import rest_framework as filters


class SnippetFilter(filters.FilterSet):

    class Meta:
        model = Snippet
        fields = {
            'title': ['icontains'],
            'created': ['iexact', 'lte', 'gte'],
        }


class SnippetViewSet(viewsets.ModelViewSet):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    filterset_class = SnippetFilter

    @action(methods=['get'], detail=False)
    def newest(self, request):
        newest = self.get_queryset().order_by('created').last()
        serializer = self.get_serializer_class()(newest)
        return Response(serializer.data)

2 个答案:

答案 0 :(得分:0)

我明确创建了过滤器。例如,以下代码将产生snippets/?snippet_field_lte=<number>snippets/?another_field=<number>端点。

class SnippetFilter(filters.FilterSet):
    snippet_field_lte = NumberFilter(name="snippet_field", lookup_expr="lte")
    another_field = NumberFilter(name="another_field", lookup_expr="exact")

    class Meta:
        model = Snippet
        fields = ["snippet_field_lte", ]

答案 1 :(得分:0)

我有相同的情况(Django后端,Angular前端)。我没有直接使用restframework过滤器,但是,您可以尝试以下方法,该方法将允许您对模型进行任何类型的查询,如官方Django Docs

中所述
class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

    def get_queryset(self):
        results = super(MyModelViewSet, self).get_queryset()
        # Instead of explicit property calling in the filter
        for key, value in self.request.GET.items():
            # I use a key/value pair from dictionary obtained from request.GET
            results = results.filter(**{key: value}) # <-- this is the "trick"
            # Then, I return the filtered queryset
            return results
        # if no parameter were provided in the request, it will return .all()
        return results

完成该操作并假设您的模型具有属性nameage,您可以发出以下GET请求:

  • localhost:8000 / mymodel?name=Jonh%20Doe->确切命名为“ Jonh Doe”
  • localhost:8000 / mymodel?name__icontains=Jonh%20D->名称包含“ Jonh D”
  • localhost:8000 / mymodel?age__gte=20->年龄大于20岁
  • localhost:8000 /->从MyModel返回所有对象