The operation django django ORM database of database operations ORM

A, ORM Introduction

Mapping relations:

  -------------------- table name "class name

  -------------------- field "property

  ----------------- table records "object class instance

ORM two major functions:

  Operating Table:

    - Create a table

    - Modify table

    - Delete table

  Operational data line:

    - CRUD

ORM pymysql use third-party tools linked database

Django can not help us create a database, it can only tell us after you've created, let go django link

Second, create the preparatory work before the table

First, create your own database

Second, in the configuration settings inside mysql database link

  sqlite3 ------ changed mysql

Copy the code
# Modify the default django sqlite3 database is MySQL 
DATABASES = {
     ' default ' : {
             ' ENGINE ' : ' django.db.backends.mysql ' , # through this link to MySQL 
            ' NAME ' : ' djangotsgl ' ,
             ' the USER ' : ' the root ' ,
             ' PASSWORD ' : ' 123456 ' ,
             ' the HOST ' :'localhost',
            'PORT':'3306',
        }
    }            
Copy the code

  After this write django will go to the default database link, then you will see an error, then the solution is below this

--init-- file three, app01

import pymysql
pymysql.install_as_MySQLdb()

Fourth, create a database table

models.py

Copy the code
class Book (models.Model):   # must inherit 
    NID = models.AutoField (primary_key = True)   # increment id (you can not write, the default will be increased from the above mentioned id) 
    title = models.CharField (max_length = 32 ) 
    publishDdata models.DateField = ()   # published 
    author = models.CharField (MAX_LENGTH = 32 ) 
    . price = models.DecimalField (max_digits =. 5, decimal_places = 2)   # total of five, with two decimal places
    
Copy the code

 Execute command to create :( need to remember !!!) 

python3 manage.py makemigrations create scripts 
python3 manage.py migrate migration

Specific examples of realization

model.py

urls.py

views.py

template /index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width">
 7     <title>Title</title>
 8     <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
 9     <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
10     <style>
11         table{
12             margin-top: 50px;
13         }
14     </style>
15 </head>
16 <body>
17 <div class="containers">
18     <div class="row">
19         <div class="col-md-9 col-md-offset-2">
20             <table class="table table-hover">
21                 <thead>
22                     <tr>
23                         <th>编号</th>
24                         <th>书名</th>
25                         <th>出版日期</th>
26                         <th>作者</th>
27                         <th>价钱</th>
28                         <th>操作</th>
29                     </tr>
30                 </thead>
31                 <tbody>
32                 {% for book in book_list %}
33                     <tr>
34                             <td>{{ book.nid }}</td>
35                             <td>{{ book.title }}</td>
36                             <td>{{ book.publishDdata|date:'Y-m-d' }}</td>
37                             <td>{{ book.author }}</td>
38                             <td>{{ book.price }}</td>
39                             <td>
40                                 <a href="/del/{{ book.nid }}"><button class="btn btn-danger">删除</button></a>
41                                 <a href="/edit/{{ book.nid }}"><button class="btn btn-success">编辑</button></a>
42                                 <a href="/add/"><button class="btn btn-primary">添加</button></a>
43                             </td>
44                     </tr>
45                 {% endfor %}
46                 </tbody>
47             </table>
48         </div>
49     </div>
50 </div>
51 </body>
52 </html>
图片内容具体,

 五、查看数据库的sql语句(加在settings.py)

Copy the code
查看数据库执行代码
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}
Copy the code

 

一、ORM介绍

映射关系:

  表名 --------------------》类名

  字段--------------------》属性

  表记录-----------------》类实例化对象

ORM的两大功能:

  操作表:

    - 创建表

    - 修改表

    - 删除表

  操作数据行:

    - 增删改查

ORM利用pymysql第三方工具链接数据库

Django没办法帮我们创建数据库,只能我们创建完之后告诉它,让django去链接

二、创建表之前的准备工作

一、自己创建数据库

二、在settings里面配置mysql数据库链接

  sqlite3------改为mysql

Copy the code
# 修改django默认的数据库的sqlite3为mysql
DATABASES = {
    'default': {
            'ENGINE': 'django.db.backends.mysql', #通过这个去链接mysql
            'NAME': 'djangotsgl',
            'USER':'root',
            'PASSWORD':'123456',
            'HOST':'localhost',
            'PORT':'3306',
        }
    }            
Copy the code

  这样写上以后django会默认的就去链接数据库,这时你会看到报错了,那么解决的办法就是下面的这样

三、app01中的--init--文件

import pymysql
pymysql.install_as_MySQLdb()

四、创建数据库表

models.py

Copy the code
class Book(models.Model):  #必须要继承的
    nid = models.AutoField(primary_key=True)  #自增id(可以不写,默认会有自增id)
    title = models.CharField(max_length=32)
    publishDdata = models.DateField()  #出版日期
    author = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5,decimal_places=2)  #一共5位,保留两位小数
    
Copy the code

 执行命令创建:(需要记住的!!!) 

python3 manage.py makemigrations   创建脚本
python3 manage.py migrate   迁移

具体例子实现

model.py

urls.py

views.py

template /index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width">
 7     <title>Title</title>
 8     <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
 9     <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
10     <style>
11         table{
12             margin-top: 50px;
13         }
14     </style>
15 </head>
16 <body>
17 <div class="containers">
18     <div class="row">
19         <div class="col-md-9 col-md-offset-2">
20             <table class="table table-hover">
21                 <thead>
22                     <tr>
23                         <th>编号</th>
24                         <th>书名</th>
25                         <th>出版日期</th>
26                         <th>作者</th>
27                         <th>价钱</th>
28                         <th>操作</th>
29                     </tr>
30                 </thead>
31                 <tbody>
32                 {% for book in book_list %}
33                     <tr>
34                             <td>{{ book.nid }}</td>
35                             <td>{{ book.title }}</td>
36                             <td>{{ book.publishDdata|date:'Y-m-d' }}</td>
37                             <td>{{ book.author }}</td>
38                             <td>{{ book.price }}</td>
39                             <td>
40                                 <a href="/del/{{ book.nid }}"><button class="btn btn-danger">删除</button></a>
41                                 <a href="/edit/{{ book.nid }}"><button class="btn btn-success">编辑</button></a>
42                                 <a href="/add/"><button class="btn btn-primary">添加</button></a>
43                             </td>
44                     </tr>
45                 {% endfor %}
46                 </tbody>
47             </table>
48         </div>
49     </div>
50 </div>
51 </body>
52 </html>
图片内容具体,

 五、查看数据库的sql语句(加在settings.py)

Copy the code
查看数据库执行代码
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}
Copy the code

 

Guess you like

Origin www.cnblogs.com/maaosheng/p/11621527.html