Learning Django-Rest-Framework

熟悉django-rest-framework

  1. 安装: pip install djangorestframework
  2. 在Django项目中注册django-rest-framework
  3. urls.py中注册log-in/log-out视图, 如不添加, 则在Browsable API中无登录功能
  4. 麻雀的五脏:
  • Serializer
  • View
  • URLS

Filters

  1. get_queryset方法可以写出更详细的queryset

    1
    2
    3
    class HREmployee(generics.ListAPIView):
    def get_queryset(self):
    return Employee.objects.filter(department="Human Resources")
  2. get_queryset中可以使用self.request, self.args, self.kwargs等参数;

  3. 通过filter_backendsfilter_fields可以通过url来筛选结果;

    1
    2
    3
    4
    class Employees(generics.ListAPIView):
    queryset = Employee.objects.all()
    filter_backends = (filter.DjangoFilterBackend, )
    filter_fields = ("department", "role", )
  4. 可以通过django_filters.rest_framework.FilterSet来定义Filter, 再用在第三种方法的filter_backends

0%