zoukankan      html  css  js  c++  java
  • Django+restframework记一次网书项目

    学习资料:

        1.django模型字段文档:https://docs.djangoproject.com/…

        2.在SQL中ntext和text类型的的区别:http://www.uzzf.com/news/2210.html

    一、搭建环境

        安装virtualenvwrapper:https://www.cnblogs.com/apollo1616/p/10222799.html

        创建虚拟环境: mkvirtualenv –-python= python.exe路径 环境名(net_book)

        进入虚拟环境:workon 环境名(net_book)

        安装依赖包:pip install django==2.2 –i https://pypi.douban.com/simple/

                         pip install pymysql # 连接MySQL数据库

                         pip install django-redis # 连接Redis数据库

                         pip install djangorestframework # RESTFual规则

                         pip install pillow # 图片处理包

    二、编辑项目

    1、创建项目:django-admin startproject 项目名(net_book) (存放项目的文件夹下)

    2、创建应用:python manage.py startapp 应用名(Book) (在项目文件夹下运行)

    3、设置settings:

              在INSTALLED_APPS中添加’rest_framework’, ‘Book’,

              LANGUAGE_CODE = ‘zh-hans’

              USE_ZONM = ‘Asia/Shanghai’

              USE_TZ = False

    4、创建模型:Pycharm连接Mysql失败. [08001] Could not create c。。。

            Ebook模型:

      1 class Ebook(models.Model):
      2     name = models.CharField(max_length=32)
      3     author = models.CharField(max_length=32)
      4     introduction = models.TextField()
      5     type = models.IntegerField(default=UNCLASSIFIED)
      6     status = models.IntegerField(default=SERIAL)
      7     price = models.DecimalField(max_digits=6, decimal_places=2, default='0')
      8     thumbnail = models.ImageField(upload_to=f'media/uploads/thumbnail/%Y/%m', default='a')
      9     bookcase_num = models.IntegerField(default=0)
     10     vote_num = models.IntegerField(default=0)
     11     weight = models.IntegerField(default=WEIGHT_DEFAULT)
     12     class Meta():
     13         db_table = 'books'
    Ebook模型:
            Content模型:
      1 class Content(models.Model):
      2     suffix1 = models.TextField(blank=True, null=True)
      3     suffix2 = models.TextField(blank=True, null=True)
      4     suffix3 = models.TextField(blank=True, null=True)
      5     suffix4 = models.TextField(blank=True, null=True)
      6     suffix5 = models.TextField(blank=True, null=True)
      7     suffix6 = models.TextField(blank=True, null=True)
      8     suffix7 = models.TextField(blank=True, null=True)
      9     suffix8 = models.TextField(blank=True, null=True)
     10     suffix9 = models.TextField(blank=True, null=True)
     11     suffix0 = models.TextField(blank=True, null=True)
     12     book = models.ForeignKey(Ebook, on_delete='PROTECT', null=True, blank=True)
     13     class Meta():
     14         db_table = 'contents'
    Content模型:
        设置settings:
      1 DATABASES = {
      2     'default': {
      3         # 'ENGINE': 'django.db.backends.sqlite3',
      4         # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
      5         'ENGINE': 'django.db.backends.mysql',
      6         'NAME': 'net_book',
      7         'USER': 'root',
      8         'PASSWORD': 'your password',
      9         'HOST': '127.0.0.1',
     10         'POST': '3306',
     11     }
     12 }
    设置settings->DATABASES:

        生成迁移文件:Python manage.py makemigrations

        迁移数据:pyhton manage.py migrate

    5、创建序列化器:

        在Books中创建serialization.py

      1 from rest_framework import serializers
      2 from Books.models import *
      3 
      4 
      5 class EbookSerializer(serializers.ModelSerializer):
      6 
      7     class Meta():
      8         model = Ebook
      9         # field = ('id', 'name', 'author', 'introduction', 'type',
     10         #          'status', 'price', 'thumbnail', 'bookcase_num',
     11         #          'vote_num', 'weight', )
     12         fields = '__all__' # 所有字段都序列化
    serialization(测试):
      1 from django.shortcuts import render
      2 from rest_framework.viewsets import ModelViewSet
      3 from Books.serialization import *
      4 
      5 class EbookInfoViews(ModelViewSet):
      6     queryset = Ebook.objects.all() # 指定查询结果集
      7     serializer_class = EbookSerializer # 指定序列化器
    views类视图(测试):
      1 from rest_framework import routers
      2 from Books import views
      3 
      4 router = routers.DefaultRouter()
      5 router.register('books', views.EbookInfoViews)
      6 print(router.urls)
      7 
      8 urlpatterns = [
      9 
     10 ]
     11 
     12 urlpatterns += router.urls
    Books.urls(测试):
      1 from django.contrib import admin
      2 from django.urls import path, include
      3 
      4 urlpatterns = [
      5     path('admin/', admin.site.urls),
      6     path('api/', include('Books.urls'))
      7 ]
      8 
    net_book.urls(测试):

    6、关联查询和序列化

      1 class ChaptersContents(APIView):
      2 
      3     def get(self, request, pk):
      4         book = Ebook.objects.get(pk=pk)
      5         chapters_content = book.content_set.all()
      6         serializer = ContentSerializer(chapters_content, many=True)
      7 	#------------------------------# 多个结果一定要指定many=True
      8 
      9         return Response(serializer.data)
    外键查询和序列化:
  • 相关阅读:
    配置Tomcat 输入ip直接访问自己的页面
    为什么hashMap的容量是2的幂次
    LinkedList源码详解
    以太网和Zigbee的家居信息采集系统
    无线LED智能照明控制系统
    ZigBee无线应变采集装置
    ZigBee红外远程监控系统设计
    ZigBee教室照明监控系统设计
    基于物联网的智能医护系统研究
    物联网的低成本乳品质量链追溯平台设计
  • 原文地址:https://www.cnblogs.com/yulincoco/p/11944500.html
Copyright © 2011-2022 走看看