django rest framework之序列化

首先找到models文件,而後裏面寫上內容,自定義數據庫

class UserGroup(models.Model):
    title = models.CharField(max_length=32)


class UserInfo(models.Model):
    name = models.CharField(verbose_name="姓名",max_length=255)
    age = models.IntegerField(verbose_name="年齡")
    choice = (
        (1, '男人'),
        (2, '女人'),
        (3, '其餘')
    )
    sex = models.IntegerField(verbose_name="性別",choices=choice)
    address = models.CharField(verbose_name="地址",max_length=255)
    ug = models.ForeignKey(UserGroup,default=1,on_delete=models.CASCADE)

而後同步數據庫,而後往數據庫裏這兩張表添加內容,完畢以後回到視圖函數,裏面寫上代碼邏輯,首先定義一個序列化類django

from rest_framework import serializers
"""
先要建立一個類繼承Serializers
"""
class UserSerializers(serializers.Serializer):
    """序列化字段和數據庫必須同樣"""
    name = serializers.CharField()
    age = serializers.CharField()
    sex = serializers.IntegerField()
    address = serializers.CharField()
    # source 來源於,就是讓頁面再也不顯示對象而是數據庫的字段
    ug = serializers.CharField(source='ug.title')

接下來開始寫邏輯代碼json

from rest_framework import views
from rest_framework.views import Response
from app1 import models

class SerializersViews(views.APIView):
    def get(self,request,*args,**kwargs):
        # user_list = models.UserInfo.objects.filter()
        user_list = models.UserInfo.objects.filter()
        # 選擇序列化類,若是是多個,many=True,若是是單個,many=False
        sls = UserSerializers(instance=user_list,many=True)
        # sls = UserSerializers(instance=user_list,many=False)
        # sls.data 已經序列化數據庫所需字段
        return Response(sls.data)

完整代碼以下:session

from django.shortcuts import render,HttpResponse
from rest_framework import views
from rest_framework import serializers
from rest_framework.views import Response
from app1 import models
# Create your views here.
"""
先要建立一個類繼承Serializers
"""
class UserSerializers(serializers.Serializer):
    """序列化字段和數據庫必須同樣"""
    name = serializers.CharField()
    age = serializers.CharField()
    sex = serializers.IntegerField()
    address = serializers.CharField()
    # source 來源於,就是讓頁面再也不顯示對象而是數據庫的字段
    ug = serializers.CharField(source='ug.title')




class SerializersViews(views.APIView):
    def get(self,request,*args,**kwargs):
        # user_list = models.UserInfo.objects.filter()
        user_list = models.UserInfo.objects.filter()
        # 選擇序列化類,若是是多個,many=True,若是是單個,many=False
        sls = UserSerializers(instance=user_list,many=True)
        # sls = UserSerializers(instance=user_list,many=False)
        # sls.data 已經序列化數據庫所需字段
        return Response(sls.data)
完整代碼

寫完以後,在你的urls裏面寫上app

from django.contrib import admin
from django.urls import path
from app1 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('Serializers/', views.SerializersViews.as_view()), # 添加這一行
]

以後在你的配置文件中ide

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app1.apps.App1Config',
    'rest_framework', # 配置上
]

好了,上面完成以後,直接啓動系統,網頁輸入url能夠看到內容了,不知道爲啥沒法粘貼圖片了,看代碼吧函數

[
    {
        "name": "陳晨",
        "age": "20",
        "sex": 1,
        "address": "河北邯鄲",
        "ug": "A組"
    },
    {
        "name": "付霞",
        "age": "15",
        "sex": 2,
        "address": "甘肅慶陽",
        "ug": "B組"
    }
]

這是用postman測試的,能夠看到已經把數據json好了post

相關文章
相關標籤/搜索