View + django-rest-framework序列化
程序员文章站
2022-05-02 16:49:19
demo目录 RestDemo ├── App │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py 数据模型 │ ├── serializers.py 序列化模块 │ ├── tests.py ......
demo目录
restdemo
├── app
│ ├── admin.py
│ ├── apps.py
│ ├── init.py
│ ├── migrations
│ ├── models.py ------------------------------------------------数据模型
│ ├── serializers.py ------------------------------------------------序列化模块
│ ├── tests.py
│ ├── urls.py
│ └── views.py ------------------------------------------------cbv(class base view) 视图函数
├── manage.py
└── restdemo
├── init.py
├── settings.py
├── urls.py
└── wsgi.py
model模块
from django.db import models class usermodel(models.model): username = models.charfield(max_length=32) age = models.integerfield() class meta: db_table = 'user'
serializers模块
# 创建序列化类 from rest_framework import serializers from app.models import usermodel class userserializer(serializers.modelserializer): class meta: model = usermodel fields = ('username', 'age')
views模块
from django.http import httpresponse, jsonresponse from django.views import view from app.models import usermodel from app.serializers import userserializer class userresource(view): def get(self, request): user = usermodel.objects.first() serializer = userserializer(user) return jsonresponse(serializer.data) def post(self, request): users = usermodel.objects.all() '对多个对象进行序列化时注意many' serializers = userserializer(users, many=true) '忽略安全性' return jsonresponse(serializers.data, safe=false)
上一篇: 又吃一顿