from App import views
from django.urls import path
app_name = "App"
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('relate/', views.RelatedObjectView.as_view(), name='relate'),
path('reView/', views.RequestView.as_view(), name='reView'),
上面是url
下面是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)
book = models.ForeignKey(Bookinfo, models.CASCADE, db_column='bid', blank=True, null=True, related_name='heros')
class Meta:
managed = True
db_table = 'heroinfo'
def __str__(self):
return self.hname
配置文件
"""
Django settings for day13 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/
"""
import os
from pathlib import Path
# 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 = '+-60e3k@e5p19i=m2kdqm6g2t5@67+(7r%14^qyjw*ox8^otu#'
# 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 = 'day13.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 = 'day13.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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
# REST_FRAMEWORK ={
# 'DEFAULT_PARSER_CLASSES': (
# 'rest_framework.parsers.JSPNParser'
# )
# }
view
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http import HttpResponse
from App.serializers import BookSrializer
from App.models import Bookinfo
class IndexView(APIView):
def get(self, request):
book = {
'btitle': '将夜',
'bpub_date': '2020-2-10',
'bread': 60,
'bcomment': 30,
'bimage': '1.jpg'
}
bs = BookSrializer(data=book)
if bs.is_valid():
# 保存到数据
bs.save()
print(bs.data)
return Response({'code': 2, 'msg': '保存成功'})
else:
print("bs.errors===========", bs.errors)
return Response({'code': 1, 'msg': bs.errors})
class RelatedObjectView(APIView):
def get(self, request):
# 序列化
books = Bookinfo.objects.all()
bs = BookSrializer(instance=books, many=True)
print(bs.data)
return Response(data=bs.data)
class RequestView(APIView):
pass
# parser_classes = (JSONParser,)
#
# def get(self, request):
# print(request.data)
# return Response({'msg': "request"})
Srializer
from rest_framework import serializers
from App.models import Bookinfo, Heroinfo
from datetime import datetime
# def validate_date(value):
# if value < datetime(2010, 1, 1).date():
# raise serializers.ValidationError("不能大于1000")
#
#
# # 自定义的序列化器
# # 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)
# # 反向序列化:将前端穿过了的数据生成对象,可以保存到数据库
#
#
# # 通过模型生成序列化
# class BookSerializer(serializers.ModelSerializer):
# """
# 图书数据序列化器
# """
# btitle = serializers.CharField(max_length=100, required=True)
# bpub_date = serializers.DateField(allow_null=True, required=False, validators=validate_date)
# bread = serializers.IntegerField(min_value=30, error_messages={
# 'min_value': '最小值不能小于30'
# })
# bcomment = serializers.IntegerField(min_value=50)
# bimage = serializers.CharField(max_length=300)
#
# # 单字段验证
# def validate_bread(self, attrs):
# if attrs > 1000:
# raise serializers.ValidationError("不能大于1000")
#
# # 多个字段验证
# # def validate(self, attrs):
# # pass
#
# def create(self, validated_data):
# print("create===================")
#
# # book = Bookinfo(btitle=validated_data.get('btitle'))
# # book.bpub_date = validated_data.get('bpub_date')
# # book.bread = validated_data.get('bread')
# # book.bcomment = validated_data.get('bcomment')
# # book.bimage = validated_data.get('bimage')
#
# return Bookinfo.objects.create(**validated_data)
#
# def update(self, instance, validated_data):
# """
# :param instance: 要更新的对象
# :param validated_data: 要更新的属性字典
# :return:对象
# """
# 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
class HeroSerializer(serializers.ModelSerializer):
class Meta:
model = Heroinfo
fields = "__all__"
class BookSrializer(serializers.ModelSerializer):
# 一般不使用上面的手动写的,用这个,可以自动生成验证
heros = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
bread = serializers.IntegerField(min_value=0)
class Meta:
model = Bookinfo
fields = '__all__'
运行结果
文件目录结构