zoukankan      html  css  js  c++  java
  • day13-3django后端开发

    一、配置

    1.修改文件目录后,需要修改的位置

    2.修改运行目录

    3.复制db路径,重新连接数据库

     2.删除数据的操作步骤

    https://blog.csdn.net/doulihang/article/details/102973565

    3.数据库多对多的生成方式

    django里面的多对多关系,它是通过建立第三张表来存储对应的关系。

    在models模块

    class Teacher(models.Model):
        name = models.CharField(max_length=50)
    
        def __str__(self):
            return self.name
    
        class Meta:
            db_table = 'teacher'
    
    class Student(models.Model):
        name = models.CharField(max_length=50,verbose_name='学生姓名')
        teacher = models.ManyToManyField(Teacher,verbose_name='老师')
    
        def __str__(self):
            return self.name
    
        class Meta:
            db_table = 'student'

    2.添加到admin中后,通过页面创建数据。查看数据库中的显示

    #新增数据,新增多对多关系
    #正向查询(在models里面有多对多的查询)
    stu = models.Student.objects.create(name="fangdan")
    stu.teacher.add(1)
    stu.teacher.add(2)
    
    # get_or_create如果存在就get,如果不存在就创建
    stu,status = models.Student.objects.get_or_create(name="李想")
    print(stu)
    stu.teacher.remove(1)#从关系里面删除一个老师
    print(stu.teacher.all())#查看所有老师
    print(stu.teacher.get(id=2))
    
    
    #反向查询,model里面没有多对多的这个字段
    teacher,status = models.Teacher.objects.get_or_create(name= '大老师')
    print(teacher.student_set.all())
    # print(teacher.student_set.remove())
    # print(teacher.student_set.add())
    print(teacher.student_set.filter())
    print(teacher.student_set.count())
    # print(teacher.student_set.clear())
    # print(teacher.student_set.create())

    4.自关联

    class Case(models.Model):
        name = models.CharField(max_length=50)
        url = models.CharField(max_length=10)
        method = models.CharField(max_length=20)
        param = models.CharField(max_length=30)
        #自关联,null=True数据不能为空,blank=True admin中不能为空
        require_case = models.ForeignKey('self',on_delete=models.PROTECT,verbose_name='依赖用例',null=True,blank=True)
    
        def __str__(self):
            return self.name
    
        class Meta:
            db_table = 'case'
            ordering = ['-id']

     5.一对一的关系

    class Account(models.Model):
        balance = models.IntegerField(verbose_name='余额',default=0)
    
        class Meta:
            db_table = 'account'
    
    class User(models.Model):
        name = models.CharField(max_length=50)
        account = models.OneToOneField(Account,on_delete=models.CASCADE,verbose_name='账户')#级联
    
        def __str__(self):
            return self.name
    
        class Meta:
            db_table = 'user'

     6.数据库路由:不同的app访问不同的数据库

    user访问sqllite,order访问的是mysql数据库

    数据库配置:sqllite是文件数据库

    pip install django_redis==4.10

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        },
        'mysql':{
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'jxz',
            'HOST': '118.24.3.40',
            'PASSWORD': '123456',
            'USER': 'jxz',
            'PORT': 3306,
        }
    }#数据库配置
    
    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://118.24.3.40:6379/0",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                "CONNECTION_POOL_KWARGS": {"max_connections": 100},
                "PASSWORD": "HK139bc&*",  # 密码
            }
        },
        "redis2": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://118.24.3.40:6379/1",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                "CONNECTION_POOL_KWARGS": {"max_connections": 100, 'decode_responses': True},
                "PASSWORD": "HK139bc&*",  # 密码
            }
        }
    }  # redis配置
    
    DATABASE_ROUTERS = ['sky.database_router.DatabaseAppsRouter'] #与下面的类的路径

    写一个数据库路由的类

    db_mapper = {
        'sqlite':'default',
        'order':'mysql'
    
    }
    
    class DatabaseAppsRouter(object):
        def db_for_read(self, model, **hints):
            print('走了读',model)
            app_label = model._meta.app_label
            if app_label in db_mapper:
                return db_mapper[app_label]
            return 'default'
    
        def db_for_write(self, model, **hints):
            print('走了写',model)
            app_label = model._meta.app_label
            if app_label in db_mapper:
                return db_mapper[app_label]
            return 'default'

    运行后django会报错,解决方法,是在sky的下面创建一个__init__.py,再启动就不会报错了

    import pymysql
    pymysql.install_as_MySQLdb()

    在order中的models中写入

    from django.db import models
    
    # Create your models here.
    class FDD(models.Model):
        name = models.CharField(max_length=50)
    
        def __str__(self):
            return self.name
    
        class Meta:
            db_table = 'Fdd'
            # app_label = 'new_user'因为是在order应用中写的,所以不用写这个
    
    
    #makemigrations order
    #migrate
    # migrate order --database mysql

    7.fvb,cvb(function(def) view,class view)

    ===参照user中的views 和order中的views的区别

    8.urls拆分

    order和user中的有views,在sky的urls中如果添加

    方法一:使用别名as

    from user import views
    # from order import views as o_view
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('',include('user.urls')),
        # path('user', o_view.UserView.as_view()),
    
    ]

    方法二:拆分

    分别在order和user中创建urls.py文件

    from . import views
    
    from django.urls import path
    
    urlpatterns = [
        path('user',views.UserView.as_view(),),
    ]
    order中的urls
    from . import views
    
    from django.urls import path
    from .import views,new_views
    
    urlpatterns = [
        path('index', views.index),
        # path('', views.get_sign),
        # path('category', views.category_view),
        path('category/<int:id>', views.category),
        path('detail/<int:id>', views.article),
        path('test', views.test),
        path('', views.index),
        path('add', views.add_article),
        path('interface', new_views.InterfaceView.as_view()),
    
    ]
    user/urls.py
    from django.contrib import admin
    from django.urls import path,include
    from user import views
    # from order import views as o_view
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('',include('user.urls')),
        path('order/',include('order.urls')),
    
    ]
    sky/urls

    9.中间件:类似上下文管理器

     

  • 相关阅读:
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    fzu2020软工作业5
    [fiddler] 使用AutoResponder功能修改http响应
    [jest] 史莱姆也能学会的前端测试
    fzu2020软工作业3
    fzu2020软工作业4
    fzu2020软工作业2
    [python] 简易代码量统计脚本
  • 原文地址:https://www.cnblogs.com/victory-0315/p/14092032.html
Copyright © 2011-2022 走看看