django -- ORM模型

* 模板加载静态文件  
* django 数据库   
* 小型项目  
* orm模型     

## 复习  

```{
add {{value|add:"adsf"}}
cut {{value|cut:""}}
context = {
    'birthday':datetime.now()
}
{{value|date:'Y-m-d H:i:s'}}  
default 

{{value|default:"默认值"}} [] {} "" None 
{{value|default_if_none:"默认值"}}
empty  
{{value|first}}
{{value|last}}
{{value|floatformat}}
{{value|join:"/"}}
{{value|length}}
{{value|lower}} 
{{value|upper}}
{{value|random}}
{{value|safe}}
{{value|stringtags}}
{{value|truncatechars:5}} 
{{value|truncatechars_html5}} 

以上是 过滤器的复习  


{%if%} 
{%elif%}
{%else%}
{%endif%}
{%for person in persons%}

    {%empty %}
    
{%end for %}

{%for key,value in persons.items%}
    {{floop.counter}}
    {{floop.counter0}}
    {{floop.recounter0}}
    {{floop.first}}
{%end for %}


{% with list = persons.0 %}
    {{list}}
{%end with %

{% with persons.0 as list %}
    {{list}}
{%end with %}


{% url "url名字" book_id=''%}

{%autoescape on%}
{%end autoescape%}


{%varbatim%}
 {{}}
{%endvarbatim%}

自定义过滤器   
    1.在应用下面 创建一个 python包 起名就叫做  templatetags
      写个 my_filter,py
      将该应用 写道 settings.py中的   INSTALLED_APPS 
    2.from django import template 
      register = template.Library()
      def myfil(value,word):
          return value+word
          
      register.filter("页面上用的名字",myfil)
      
      {% load my_filter%}

{%include "header.html" with username=""%}


base.html 

{%block content%}
 
{%endblock%}


{%extends "base.html"%}
    {%block.super%}
    {%block content%}
{%endblock%}
     
{%endblock%}
```

## 模板 template加载 静态文件   

> 在 DTL中 使用 static 来加载  静态文件  如果想要使用  还必须   {% load static%}

加载静态文件的步骤如下: 

1.确保 'django.contrib.staticfiles' 已经加入到了  INSTALLED_APPS

2.STATIC_URL 确保setting.py中设置了  #127.0.0.1/static/1.jpg #在浏览器中请求 静态文件的url 

3.首先在应用下面 新建一个 目录  叫 static  在static 目录下面  再创建一个 以 app 名字 命名的 目录 

4.到 INSTALLED_APPS  注册 你的应用   

### 当static 不跟 所有的应用挂钩   需要这么操作 全局static样式  

```django
settings.py 最后行加入   
STATICFILES_DIRS  = [
    os.path.join(BASE_DIR, 'static')
]

static 跟  templates 同级  
```

## 如果不想每次加载静态文件   都 {%load static %} 在 settings.py中 加入  

```python
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',
                
            ],
            'builtins':['django.templatetags.static'],  #在这里加入  
        },
    },
]
```

## django数据库   

```
django 操作 mysql  底层还是python操作mysql  想操作没问题  必须安装扩展或者叫做 驱动程序  

pymysql  纯python 写的  执行效率不如 MySQL-python 高 
MySQL-python c语言写的  只支持puthon2  不支持python3  
mysqlclient MySQL-python 的一个分支  修复了bug 支持了python3 

综上考虑  选择 mysqlclient  

https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient 下载下来之后 放到 一个  目录下面  
然后 pip install mysqlclient-1.3.13-cp36-cp36m-win_amd64.whl  即可 
```

## django 操作数据库  

```python
settings.py中 有一个 

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_db', #数据库的名字
        'USER':'root', #用户名 
        'PASSWORD':'123456', #密码
        'HOST':'127.0.0.1', #连接地址
        'PORT':'3306' #端口号 
     }
}


from django.shortcuts import render
from django.db import connection

def index(request):
    cursor = connection.cursor()
    #cursor.execute("insert into book(name,author) values('三国演义','罗贯中'),('红楼梦','曹雪芹')")
    cursor.execute("select * from book")
    rows = cursor.fetchall()
    for row in rows:
        print(row)
    #rows = cursor.fetone()
    #rows = cursor.fetchmany(2)
    return render(request,'index.html')
```

## 实战项目  

```

```

### ORM 模型    

```
项目增大 sql语句越来越复杂  大量采用 原声sql语句 会出现以下问题  : 
    1.重复利用率不高  需要写多个重复的sql语句  
    2.好多程序员 容易忽略 安全问题容易导致 sql注入 
    3.如果哪天业务逻辑放生变化  我们需要修改多条sql语句  容易遗漏某些sql语句  导致报错   
    
为了解决这个问题 就出现了 ORM object relational Mapping  对象关系映射 通过ORM 我们可以使用 类来操作mysql 不用写原生sql语句   把每个数据表映射为一个类 数据行映射为一个个实例 字段映射为属性    


1.这样 减少重复利用的概率   看起来直观清晰  
2. ORM归根到底 是 转化为原声sql语句去操作数据库  有人觉得 转化过程容易出现损耗  损耗不会超过5%  
3.写复杂的查询 更简单  
4.可以将ORM移植到 sqlite mysql等   
```

## 创建 ORM 模型  

```python
创建 应用  并到 settings.py中 注册应用  
    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'book',
]
到应用下面 的 models.py  

from django.db import models

#如果想要将普通的一个类 映射为 数据库中的ORM模型
# 必须继承  models.Model
class Book(models.Model):
    #1.id int(11)  自增长
    id = models.AutoField(primary_key=True)
    #2.name varchar(100) not null
    name = models.CharField(max_length=100,null=False)
    #3.author varchar(100) not null
    author = models.CharField(max_length=100,null=False)
    #4.price float not null
    price = models.FloatField(null=False,default=0)
    
接下来  
python manage.py makemigrations   生成迁移脚本   

(my_env) c:\www\db\_intr_demo>python manage.py migrate #映射到数据库中   
Operations to perform:
  Apply all migrations: admin, auth, book, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying book.0001_initial... OK
  Applying sessions.0001_initial... OK
  
  
  settings.py中  INSTALLED_APPS 写了多少 就创建多少模型  
  
  
  
  
  
```

## ORM 增删该查 

```python
from django.shortcuts import render
from .models import Book
from django.http import HttpResponse

# Create your views here.
def index(request):
    #添加数据到数据库中
    # book = Book(name="金瓶梅",author='兰陵笑笑生',price='1000')
    # book.save()

    #查询数据库
    # book = Book.objects.get(pk=1)
    # print(book)

    # books = Book.objects.filter(name="金瓶梅").first()
    # print(books.price)
    
    
    #添加数据
    # book = Book(name="三国演义",author="罗贯中",price='300.00')
    # book.save()

    #删除数据
    # book = Book.objects.get(id=3)
    # book.delete()

    #更改数据
    # book = Book.objects.get(id=2)
    # book.name = "红楼梦"
    # book.author = "曹雪芹"
    # book.price = '260'
    # book.save()

    #查找数据
    # book = Book.objects.get(id=4)
    # print(book.name)
    return HttpResponse("图书添加成功")

```

猜你喜欢

转载自blog.csdn.net/qq_42336700/article/details/82765385
今日推荐