rest_framework的序列化的一个简单示例

1.配置文件

"""
Django settings for day11 project.

Generated by 'django-admin startproject' using Django 3.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'g1@oqc)9cjvqiadz%q(@c_1_$x4^&q!=v^5#$5t=t)@sdlh$8u'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'App.apps.AppConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'day11.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'day11.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'day11',
        'HOST': '127.0.0.1',
        'USER': 'root123',
        'PASSWORD': '123456',
        'PORT': 3306
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'




2.url

from App import views
from django.urls import path
app_name = "App"
urlpatterns = [
    # path('book/<int:bid>/', views.BooksView.as_view(), name='book'),
    path('example/', views.ExampleView.as_view(), name='example'),

3.model

# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models


class User(models.Model):
    uid = models.AutoField(primary_key=True)
    username = models.CharField(unique=True, max_length=30)
    password = models.CharField(max_length=120)
    regtime = models.DateTimeField()
    sex = models.IntegerField(blank=True, null=True)
    is_active = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'user'


class Bookinfo(models.Model):
    btitle = models.CharField(max_length=200)
    bpub_date = models.DateField(blank=True, null=True)
    bread = models.IntegerField()
    bcomment = models.IntegerField()
    bimage = models.CharField(max_length=200, blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'bookinfo'

    # 对象转字典,建立一个类对象的一个方法
    def obj_to_dict(self):
        return {
            'btitle': self.btitle,
            'bpub_date': self.bpub_date,
            'bread': self.bread,
            'bcomment': self.bcomment,
            'bimage': self.bimage
        }


class Heroinfo(models.Model):
    hid = models.AutoField(primary_key=True)
    hname = models.CharField(max_length=50)
    bid = models.ForeignKey(Bookinfo, models.DO_NOTHING, db_column='bid', blank=True)

    class Meta:
        managed = True
        db_table = 'heroinfo'

2.新建的python文件
serializers

from rest_framework import serializers
from App.models import Bookinfo

# 自定义的序列化器
class BookSerializer(serializers.Serializer):
    btitle = serializers.CharField(max_length=100)
    bpub_date = serializers.DateField()
    bread = serializers.IntegerField(min_value=0)
    bcomment = serializers.IntegerField(min_value=0)
    bimage = serializers.CharField(max_length=300)

    def create(self, validated_data):
        return Bookinfo.objects.get(pk=1)

    def update(self, instance, validated_data):
        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        instance.bimage = validated_data.get('bimage', instance.bimage)
        instance.save()
        return instance


3.view

from django.views import View

from App.models import User, Bookinfo
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
import json
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from App.serializers import BookSerializer


# Create your views here.

# 前后端分离,这个是非DRF版本
# 后端需要向前端提供JSON数据
# class BooksView(View):
#     # 查询所有图书
#     def queryset_to_list(self, querset):
#         res = []
#         for obj in querset:
#             res.append(obj.obj_to_dict())
#         return res
#
#     def get(self, request, *args, **kwargs):
#         books = Bookinfo.objects.all()
#         print(books)
#         return JsonResponse(self.queryset_to_list(books), safe=False)
#
#     # 前端提交的数据,获取前端用POST提交过来的数据
#     # 传过来的数据是json对象,json对象在我们这里就是字典dict获取
#     # return是给客户端返回的信息展示
#     # 增加图书
#     def post(self, request, *args, **kwargs):
#         data = request.POST.dict()
#         Bookinfo.objects.create(**data)
#         return JsonResponse({
#             'code': 1,
#             'msg': "创建成功"
#         })
#
#     def put(self, request, bid):
#         book = Bookinfo.objects.get(pk=bid)
#         # 获取put传参,参数必须是json格式
#         data = request.body.decode()
#         data = json.loads(data)
#         book.__dict__.update(data)
#         book.save()
#         return JsonResponse({
#             'code': 1,
#             'msg': "创建成功"
#         })
#
#     def delete(self, request):
#         pass
class ExampleView(GenericAPIView):
    def get(self, request, *args, **kwargs):
        book = Bookinfo.objects.get(pk=1)
        # 序列化,把Bookinfo.objects.get(pk=1)转换成内置的列表或者字典
        # 如果是需要查询多条记录的话,我们需要增加many=True ,serializer = BookSerializer(instance=book,many=True)
        serializer = BookSerializer(instance=book)
        print(serializer.data)
        return Response(serializer.data)

文件目录
在这里插入图片描述
最后运行结果:
在这里插入图片描述
不知道为啥,每次样式都不出来

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值