zoukankan      html  css  js  c++  java
  • django项目序列化serializers

    第一步,安装

    pip install djangorestframework

    第二步,在settings.py里去注册应用

    INSTALLED_APPS = ['rest_framework'
    ]

    第三步,在合适的路径下创建一个serializers.py文件,内容如下:

    主要目的:

    1. 我们django中view视图要返回一个json字符串,如果想返回一个嵌套型或者复杂一些的字符串,就需要用到序列化
    2. 是获取不同表的字段,将多个表中的字段集中为一个大的集合,方便调用

    1.model指定序列化的表

    2.fields指定需要的字段

    3.将一个序列化的实例放入到另一个序列化里,那么在这个当前序列化里也可以调用这个实例的字段,也就是把2个表中的字段集合到了一起

    from rest_framework import serializers
    from .models import News,NewsCategory,Comment
    from apps.xfzauth.serializers import UserSerializer
    
    class NewsCategorySerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = NewsCategory
            fields = ['id','name']
    
    
    class NewsSerializer(serializers.HyperlinkedModelSerializer):
        category = NewsCategorySerializer()
        author = UserSerializer()
        class Meta:
            model = News
            fields = ['id','title','desc','thumbnail','category','author','pub_time']
    
    
    class CommentSerializer(serializers.HyperlinkedModelSerializer):
        author = UserSerializer()
        class Meta:
            model = Comment
            fields = ['id','content','author','pub_time']

    第四步,在视图中导入serializers.py文件,调用此文件把要序列化的实例放进去实现序列,然后在通过ajax把数据得到

    many=True:表示queryset对象,False表示为model对象,默认为False

    def news_comment(request):
        commentform = CommentForm(request.POST)
        print(request.POST)
        print(commentform.is_valid())
        if commentform.is_valid():
            content = commentform.cleaned_data.get('content')
            news_id = commentform.cleaned_data.get('news_id')
            news = News.objects.get(pk=news_id)
            comment = Comment.objects.create(content=content,news=news,author=request.user)
            serializer = CommentSerializer(comment,many=True)
            return restful.result(data=serializer.data)
        else:
            return restful.params_error(message=commentform.get_errors())
  • 相关阅读:
    Thinking in Ramda: Getting Started
    计算机网络 第一章 绪论(习题)
    URI和URL傻傻分不清
    mac下安装sshpass并配置自动登录
    项目 NodeJS 版本锁定及自动切换
    项目部署篇(一)后端springboot项目打包和部署
    安卓开启GPS,native.js
    native.js,安卓判断APP是否在电池优化白名单
    Self-Supervised Visual Representations Learning by Contrastive Mask Prediction
    wireshark抓包工具使用介绍(附图)
  • 原文地址:https://www.cnblogs.com/fengzi7314/p/12729286.html
Copyright © 2011-2022 走看看