zoukankan      html  css  js  c++  java
  • DRF 筛选

    from rest_framework.generics import ListAPIView,CreateAPIView,UpdateAPIView,RetrieveAPIView,DestroyAPIView
    from rest_framework.filters import BaseFilterBackend
    from rest_framework import serializers
    from rest_framework.pagination import PageNumberPagination
    from newapi import models
    
    class ArticleSerializer(serializers.ModelSerializer):
        author_name = serializers.CharField(source="author.username",required=False)
        class Meta:
            model = models.Article
            exclude = ['author']
            
    class ArticleFilter(BaseFilterBackend):
        """
        查询:根据URL中的cagetory参数查询
        """
        def filter_queryset(self, request, queryset, view):
            val = request.query_params.get('cagetory')
            if val:
                return queryset.filter(category = val)
            return queryset
    
    class ArticleView(ListAPIView,CreateAPIView):
        # queryset对象
        queryset = models.Article.objects.all()
        # 序列化
        serializer_class = ArticleSerializer
        # 筛选规则
        filter_backends = [ArticleFilter,]
        # 分页
        pagination_class = PageNumberPagination
    
        def perform_create(self,serializer):
            serializer.save(author_id=2)
    
  • 相关阅读:
    微信jssdk
    php读取大文件
    PHP工程师突破
    TCP/IP
    基于scrapy-redis的分布式爬虫
    pymongodb的使用和一个腾讯招聘爬取的案例
    中间件使用之(UA,IP,selenium)的使用
    windos下redis服务的后台启动
    mongodb的初步使用
    windos下安装mongodb
  • 原文地址:https://www.cnblogs.com/os-linux/p/11815382.html
Copyright © 2011-2022 走看看