zoukankan      html  css  js  c++  java
  • django自带的序列化组件

    如果发现可以使用MySQL无法使用sqlit3按照之前MySQL的操作安装sqlit3的驱动

    需求:前端获取到后端用户表里面的所有数据 并且是列表套字典的形式

    import json
    from django.http import JsonResponse
    from django.core import serializers
    def ab_ser(request):
        user_queryset = models.User.objects.all()
        # [{},{},{},{},{}]
        # user_list = []
        # for user_obj in user_queryset:
        #     tmp = {
        #         'pk':user_obj.pk,
        #         'username':user_obj.username,
        #         'age':user_obj.age,
        #         'gender':user_obj.get_gender_display()
        #     }
        #     user_list.append(tmp)
        # return JsonResponse(user_list,safe=False)
        # return render(request,'ab_ser.html',locals())
    
        # 序列化
        res = serializers.serialize('json',user_queryset)
        """会自动帮你将数据变成json格式的字符串 并且内部非常的全面"""
        return HttpResponse(res)
    """
    [
     {"pk": 1, "username": "jason", "age": 25, "gender": "male"}, 
     {"pk": 2, "username": "egon", "age": 31, "gender": "female"},
     {"pk": 3, "username": "kevin", "age": 32, "gender": "others"}, 
     {"pk": 4, "username": "tank", "age": 40, "gender": 4}
     ]
    前后端分离的项目
        作为后端开发的你只需要写代码将数据处理好
        能够序列化返回给前端即可 
            再写一个接口文档 告诉前端每个字段代表的意思即可
            
            
    [
    {   "model": "app01.user", 
        "pk": 1, 
        "fields": {"username": "jason", "age": 25, "gender": 1}}, 
        
    {   "model": "app01.user", 
        "pk": 2, 
        "fields": {"username": "egon", "age": 31, "gender": 2}}, 
        
    {   "model": "app01.user", 
        "pk": 3, 
        "fields": {"username": "kevin", "age": 32, "gender": 3}},
         
    {   "model": "app01.user", 
        "pk": 4, 
        "fields": {"username": "tank", "age": 40, "gender": 4}}
    ]
    写接口就是利用序列化组件渲染数据然后写一个接口文档 该交代交代一下就完事
    """
  • 相关阅读:
    微信小程序 checkbox 组件
    微信小程序 button 组件
    h5视频标签 video
    h5离线缓存
    ECharts插件介绍(图表库)
    rich-text 副文本组件 text文本组件
    progress组件(进度条)
    icon组件
    movable-view组件
    android 双击图片变大,缩放功能
  • 原文地址:https://www.cnblogs.com/mayrain/p/13038857.html
Copyright © 2011-2022 走看看