加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

python的Web框架,Django的ORM,模型基础,MySQL连接配置及增删

发布时间:2020-12-15 17:16:15 所属栏目:大数据 来源:网络整理
导读:h1 id="django中的orm简介" data-source-line="1"Django中的ORM简介 h5 id="orm概念对象关系映射object-relational-mapping简称orm" data-source-line="2"ORM概念:对象关系映射(Object Relational Mapping,简称ORM): p data-source-line="3"用面向对象的

<h1 id="django中的orm简介" data-source-line="1">Django中的ORM简介
<h5 id="orm概念对象关系映射object-relational-mapping简称orm" data-source-line="2">ORM概念:对象关系映射(Object Relational Mapping,简称ORM):
<p data-source-line="3">用面向对象的方式描述数据库,去操作数据库,甚至可以达到不用编写SQL语句就能够对数据库进行增删改查,进行各种操作。我们只需要对python的面向对象熟悉,就可以很清晰的知道各种数据之间的关系。


<p data-source-line="5">

<img src="https://www.52php.cn/res/2019/03-02/09/d67f51edba8168eeff72e60a9814da2f.png" alt="">

<p data-source-line="7">django模型映射关系:<span class="Apple-converted-space">?


<p data-source-line="7"><span class="Apple-converted-space">

<img src="https://www.52php.cn/res/2019/03-02/09/cdbb9a56f47647ca1680de8e777642dc.png" alt="">


<h4 id="django-连接mysql的配置流程" data-source-line="28">Django 连接MySQL的配置流程:


<ul data-source-line="29">

  • 安装 pymysql,用于python操作mysql数据库
  • pip install pymysql

      创建数据库用户,需要有创建数据库权限的用户

    • 创建数据库

    
    
    >>>(django) pyvip@Vip:~$ mysql -uroot -pqwe123
    
    
    >>>mysql>1 row affected (0.00 sec)
      修改setting配置,
    默认的是:: DATABASES = : : : : : : }

    <ul data-source-line="62">

  • 修改项目文件夹(和setting.py文件所在的目录)下的__init__.py文件
  • 
    
    pymysql.install_as_MySQLdb()

    <ul data-source-line="73">

  • 设置时区
  • TIME_ZONE =

      模型类必须写在app下的models.py文件中。
    1. 模型如果需要映射到数据库,所在的app必须被安装。
    2. 一个数据表对应一个模型类,表中的字段,对应模型中的类属性。

    django.db name = models.CharField(max_length=20 age = models.SmallIntegerField(default= sex = models.SmallIntegerField(default=1 qq = models.CharField(max_length=20,default= phone = models.CharField(max_length=20,default= c_time = models.DateTimeField(verbose_name=,auto_now_add= % (self.name,self.age)
    =qq、phone给的CharField不用SmallIntegerField类型的,是因为字符串更好操作,不容易出错。</span></pre>

    <ol data-source-line="121">

  • 每一个模型都是django.db.models.Model的子类(类的继承)。
  • 每个模型都有许多的类变量,它会表示模型中的数据库字段。
  • 每一个字段都由一个字段类的实例来表示。
    1. 在项目中注册app
    INSTALLED_APPS = ]
      运行数据库迁移命令(一定要在项目根目录下) 告诉django,我们做了哪些数据库的更改

    (django) pyvip@Vip:~/code/<span style="color: #000000;">crm$ python manage.py makemigrations teacher
    Migrations <span style="color: #0000ff;">for <span style="color: #800000;">'<span style="color: #800000;">teacher<span style="color: #800000;">'<span style="color: #000000;">:
    teacher/migrations/<span style="color: #000000;">0001_initial.py
    - Create model Students

    <p data-source-line="143">运行成功后,会生成一个数据库迁移文件


    <p data-source-line="145">现在还没有真正的操作数据库


    <p data-source-line="147">

    <img src="https://www.52php.cn/res/2019/03-02/09/80d96a0eea5d001e3316a2fa60ba922a.png" alt="">

    <p data-source-line="150">sqlmigrate,从迁移获取SQL语句


    <div class="cnblogs_code">

    
    

    (django) pyvip@Vip:~/code/crm$ python manage.py sqlmigrate teacher 0001<span style="color: #000000;">
    BEGIN;
    --
    --<span style="color: #000000;"> Create model Students
    --<span style="color: #000000;">
    CREATE TABLE teacher_students (id integer AUTO_INCREMENT NOT NULL PRIMARY KEY,name varchar(20) NOT NULL,age smallint NOT NULL,sex smallint NOT NULL,qq varchar(20) NOT NULL,phone varchar(20) NOT NULL,c_time datetime(6<span style="color: #000000;">) NOT NULL);
    COMMIT;

    <span style="color: #008000;">#<span style="color: #008000;">创建的表名是:appname_模型name.lower(小写)

    <ol start="3" data-source-line="165">

  • 运行migrate命令,使迁移生效
  • (django) pyvip@Vip:~/code/<span style="color: #000000;">crm$ python manage.py migrate teacher
    Operations to perform:
    Apply all migrations: teacher
    Running migrations:
    Applying teacher.0001_initial... OK

    <span style="color: #008000;">#<span style="color: #008000;">执行了teacher.0001_initial这个里面的tables。

    <p data-source-line="178">我们查看下是否创建了


    <div class="cnblogs_code">

    >>>mysql>+-------------------+
    | Tables_in_crm     |
    +-------------------+
    | django_migrations |
    | teacher_students  |
    +-------------------+
    2 rows  set (0.00这里生成了两张表:
    第一张表用来记录django的migrations
    第二张表是我们需要的数据表

    <p data-source-line="193">查看表结构:


    <div class="cnblogs_code">

    >>>mysql>+--------+-------------+------+-----+---------+----------------+
    | Field  | Type        | Null | Key | Default | Extra          |
    +--------+-------------+------+-----+---------+----------------+
    | id     | int(11)     | NO   | PRI | NULL    | auto_increment |
    | name   | varchar(20) | NO   |     | NULL    |                |
    | age    | smallint(6) | NO   |     | NULL    |                |
    | sex    | smallint(6) | NO   |     | NULL    |                |
    | qq     | varchar(20) | NO   |     | NULL    |                |
    | phone  | varchar(20) | NO   |     | NULL    |                |
    | c_time | datetime(6) | NO   |     | NULL    |                |
    +--------+-------------+------+-----+---------+----------------+
    7 rows  set (0.00<span style="color: #008000;">#<span style="color: #008000;">此处表可以看到会根据我们的定义的模型来创建。


    
    
    >>>python manage.py shell

    <h3 id="增加" data-source-line="225">增加


    <pre data-source-line="226"><code class="hljs"><span class="hljs-meta">#<span class="bash"><span class="zh-hans">导入模型
    <div class="cnblogs_code">

    
    >>> teacher.models  Students 

    <p data-source-line="230">查询模型中是否有数据


    <div class="cnblogs_code">

    >>><span style="color: #000000;">Students.objects
    <django.db.models.manager.Manager at 0xb2e0fe0c>

    <p data-source-line="238">查询模型中的所有的值


    <div class="cnblogs_code">

    >>>
    

    <span style="color: #008000;">#<span style="color: #008000;">此时我们还未添加数据,所以此处为空

    
    
    >>>s1 = Students(name=,age=18,qq=需要保存才可以操作数据库
    >>>s1.save()

    <p data-source-line="255">是否创建成功了呢,我们在MySQL中查看一下


    <div class="cnblogs_code">

    mysql> select * +----+--------+-----+-----+--------+-------+----------------------------+
    | id | name   | age | sex | qq     | phone | c_time                     |
    +----+--------+-----+-----+--------+-------+----------------------------+
    |  1 | 小明   |  18 |   1 | 123456 |       | 2019-02-26 08:04:57.955584 |
    +----+--------+-----+-----+--------+-------+----------------------------+
    1 row  set (0.00<span style="color: #008000;">#<span style="color: #008000;">这里创建的时间一定是UTC时间,因为项目会运行在不同的时区,取出来的时候再转换成当前时间就好了。

    % (self.name,self.age)

    >>>]>
    >>>s2 =>>>s2.name = <span style="color: #800000;">'<span style="color: #800000;">小明<span style="color: #800000;">'

    s2.age = 18

    s2.qq = <span style="color: #800000;">'<span style="color: #800000;">123456<span style="color: #800000;">'

    >>>Students.objects.create(name=,qq=

    <span style="color: #008000;">#<span style="color: #008000;">返回查询集

    <h5 id="第四种方式先查查了再创建" data-source-line="294">第四种方式,先查,查了再创建


    <div class="cnblogs_code">

    >>>Students.objects.get_or_create(name=<span style="color: #008000;">#<span style="color: #008000;">没有创建成功,数据存在返回查到的值
    第一个元素代表模型对象,bool值代表是否创建,False代表没有创建是查询的。


    返回的是一个查询集,不是对象,没有操作数据库,可以查看到SQL语句

    >>>,,,]>

    <span style="color: #008000;">#<span style="color: #008000;">我们添加一些数据后,用于查询出来的结果

    <p data-source-line="314">查看all语句的背后的操作,查看sql语句


    <div class="cnblogs_code">

    >>>res =>>><span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
    SELECT teacher_students.id,teacher_students.name,teacher_students.age,teacher_students.sex,teacher_students.qq,teacher_students.phone,teacher_students.c_time FROM teacher_students

    <span style="color: #008000;">#<span style="color: #008000;">就相当于SQL语句: SELECT * FROM 'teacher_students'

    <p data-source-line="323">切片方式


    <div class="cnblogs_code">

    >>>res =>>><span style="color: #0000ff;">print(res[1:2<span style="color: #000000;">].query)
    SELECT teacher_students.id,teacher_students.c_time FROM teacher_students LIMIT 1 OFFSET 1

    <span style="color: #008000;">#<span style="color: #008000;">通过切片的方式达到LIMIT的SQL语句

    <h5 id="get方法" data-source-line="333">get方法


    <p data-source-line="334">当我们的get匹配到多条数据的时候会报错。


    <div class="cnblogs_code">

    >>>Students.objects.get(name=
    

    <span style="color: #008000;">#<span style="color: #008000;">如果给定的查询内容,可以匹配到多条数据,则会报错,get方法只能获取单挑且唯一的数据

    <p data-source-line="339">pk:参数中pk代表主键


    <div class="cnblogs_code">

    >>>Students.objects.get(pk=1]>
    

    <span style="color: #008000;">#<span style="color: #008000;">同样可以查询到,pk代表主键

    <h5 id="filter方法" data-source-line="347">filter方法
    <div class="cnblogs_code">

    >>>res = Students.objects.filter(sex=1>>><span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
    SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.sex = 1


    >>>s = Students.objects.get(name=>>>s.age = 16

    s.save()

    >>>Students.objects.filter(name=).update(age=191

    <h3 id="删除" data-source-line="378">删除


    <h5 id="delete" data-source-line="379">delete方法
    <p data-source-line="380">指定删除,通过对象查到数据,再删除对象


    <div class="cnblogs_code">

    >>>s = Students.objects.get(pk=2>>><span style="color: #000000;">s.delete()
    (1,(<span style="color: #800000;">'<span style="color: #800000;">teacher.Students<span style="color: #800000;">': 1<span style="color: #000000;">))

    <span style="color: #008000;">#<span style="color: #008000;">返回的是一个元祖:删除的数量,表的名称,删除数量

    >>>Students.objects.filter(sex=13,(: 3))

    teacher.models students = Students.objects.all()

    <p data-source-line="407">对应的html中配置


    <ol data-source-line="408">

  • 获取值的方式和字典的方式一样,不用再另外配置
  • 下一篇内容:模型属性,及数据库进阶查询,

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读