drf自定义筛选

1,表结构设计

  •   不会经常变化的值放在内存:choices形式,避免跨表性能低
      分表:如果表中列太多,大量内容可以选择水平分表
      表自关联
    
    

2,一次增加两个表中的数据

  •     def post(self, request, *args, **kwargs):
            ser = serializer.ArticleListSerializer(data=request.data)
            ser_content = serializer.AddArticleSerializer(data=request.data)
            if ser.is_valid() and ser_content.is_valid():
                article_obj = ser.save()
                ser_content.save(article=article_obj)
                return Response("添加成功")
            return Response("添加失败")
    

3,筛选

  • 在文章列表时,添加筛选功能

  •     def get(self, request, *args, **kwargs):
            pk = kwargs.get("pk")
            if not pk:
                # 筛选
                condition = {}
                category = request.query_params.get("category")
                if category:
                    condition["category"] = category
                    queryset = models.Article.objects.filter(**condition).order_by("-date")
                else:
                    queryset = models.Article.objects.all().order_by("-date")
                # 分页
                page_obj = PageNumberPagination()
                result = page_obj.paginate_queryset(queryset, request, self)
                ser = serializer.ArticleListSerializer(instance=result, many=True)
                return Response(ser.data)
    
posted @ 2019-11-23 16:02  阿浪阿浪  阅读(299)  评论(0编辑  收藏  举报