[Django系列]5.数据库models

ORM (对象关系映射-Object Relational Mapping)

可以面向对象编程语言里不同类型系统的数据之间的转换.
模型model与数据库

model通常位于app/models.py

1.新建一个Book,Author的模型

#models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import modelsclass Book(models.Model):    #创建一个Book的模型,里面包含isbn,name,price三个字段
    isbn=models.IntegerField()   #整型
    name=models.CharField(max_length=100)  #字符串型,最大长度100
    price=models.FloatField()   #字符串类型
    def __unicode__(self):   #定义成员方法unicode,当函数实例化时,打印返回描述
        return self.nameclass Author(models.Model):
    name=models.CharField(max_length=30)
    age=models.IntegerField()
    def __unicode__(self):
        return self.name
创建本地映像文件“

需要注意的是,执行此项操作,必须先将应用添加到对应的settings.py的install_app列表

#settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'book',    #不添加的数,无法创建改应用的映射
]

开始创建python manage.py makemigrations

>>python manage.py makemigrations
执行效果
Migrations for 'book':
  book\migrations\0001_initial.py
    - Create model Author
    - Create model Book
映射本地文件到数据库python manage.py migrate
>>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 book.0001_initial... OK      #如果前面没有添加INSTALLED_APPS,是不会有这个表的记录
  Applying sessions.0001_initial... OK
以上步骤完成后,数据库就成功创建好了.

2.python manage.py shell 操作数据库

python manage.py shell

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
2.1创建一条记录
Author.objects.create(name="yangfan",age=25)
>>Author.objects.create(name="yangfan",age=25)
<Author: yangfan> 
######遇到重复依然是可以插入
 >>> Author.objects.create(name="yangfan",age=25)
<Author: yangfan>
但是由于这种方式创建的记录,名字相同时,不会检测报错,所以往往使用
Author.objects.get_or_create(name="fusheng",age=29)
进行创建
>>> Author.objects.get_or_create(name="fusheng",age=29)
(<Author: fusheng>, True)
>>> Author.objects.get_or_create(name='Fusheng',age=29)
(<Author: Fusheng>, True)
​
 >>> Author.objects.get_or_create(name="fusheng",age=29) #如果检测到重复,则返回错误.不再继续插入数据
(<Author: fusheng>, False)
2.2查询数据
get()方式
>>> Author.objects.get(name="fusheng")
<Author: fusheng>
>>> Author.objects.get(name="fusheng").name
u'fusheng'
>>> Author.objects.get(name="fusheng").age
29
需要注意的是,get()只能获取单条记录,如果对象的记录数大于1,则会返回如下错误
>>Author.objects.get(name="yangfan")
#错误提示:获取多于1条记录,所以这个时候
MultipleObjectsReturned: get() returned more than one Author -- it returned 2!
为了解决上述问题,可以使员工
filter()方式
返回的是一个queryset对象,是一个列表,自然可以切片
>>> Author.objects.filter(name='yangfan')
<QuerySet [<Author: yangfan>, <Author: yangfan>]>
#当然也可以使用切片的方式
>>> Author.objects.filter(name='yangfan')[0]
<Author: yangfan>
2.3过滤查询的对象
>>> Author.objects.filter(name__exact='fusheng') #严格匹配查询,匹配到fusheng返回结果
<QuerySet [<Author: fusheng>]>
>>> Author.objects.filter(name__iexact='fusheng')#不区分大小写查询
<QuerySet [<Author: fusheng>, <Author: Fusheng>]>
>>> Author.objects.filter(name__contains='sheng') #模糊查询,包含sheng字符串的对象都能被查询出来,类似like
<QuerySet [<Author: fusheng>, <Author: Fusheng>]>
>>> Author.objects.filter(name__regex='sheng$')   #正则匹配方式查询,以sheng结尾的结果都能被查询
<QuerySet [<Author: fusheng>, <Author: Fusheng>]>
>>> Author.objects.filter(name__iregex='^fu')    #不区分大小写的正则匹配查询
<QuerySet [<Author: fusheng>, <Author: Fusheng>]>
2.4排除,排序连锁查询
>>> Author.objects.exclude(name='fusheng')  #排除name='fusheng'的记录
<QuerySet [<Author: yangfan>, <Author: yangfan>, <Author: Fusheng>]>>>> Author.objects.filter(name__regex='u').exclude(name__contains="fan") #排除name中包含u,且不包含fan的记录
<QuerySet [<Author: fusheng>, <Author: Fusheng>]>>> Author.objects.order_by('name')  #按name的ascii码顺序进行顺序排序,所以大写字母靠前
<QuerySet [<Author: Fusheng>, <Author: fusheng>, <Author: yangfan>, <Author: yangfan>]>
>>> Author.objects.order_by('-name') #按name的ascii码顺序进行倒序排序
<QuerySet [<Author: yangfan>, <Author: yangfan>, <Author: fusheng>, <Author: Fusheng>]>
>>> Author.objects.filter(name__contains='n').order_by('-name') #查询name中包含n的记录按name倒序排列
<QuerySet [<Author: yangfan>, <Author: yangfan>, <Author: fusheng>, <Author: Fusheng>]>
2.5更新
save()法
注意:只能使用get()获取对象
>>> p=Author.objects.get(name='Fusheng') #获取对象赋值给p
>>> p.age
31
>>> p.age=18
>>> p.save()
这种方法等于执行了,把所有的字段都更新一遍
Author.objects.filter(name='Fusheng').update(age='29',age='Fusheng')
update()方法
注意:只能使用filter()方法获取queryset对象
>>> Author.objects.filter(name='Fusheng')[0].age
18
>>> Author.objects.filter(name='Fusheng').update(age='29')  #使用update进行修改
1
>>> Author.objects.filter(name='Fusheng')[0].age
29
2.6删除delete()
>>> Author.objects.filter(name='Fusheng')[0].age
29
>>> Author.objects.filter(name='yangfan')[0].delete()
(1, {u'book.Author': 1}) #返回操作的记录数
#删除全表操作
>>Author.objects.all().delete()
也可以使用以下方式删除
>>> p=Author.objects.get(name='Fusheng')
>>> p.delete()

作业

输入127.0.0.1:8000/books/python/?name=”zhangsan”&age=40或127.0.0.1:8000/books/python/zhangsan/40把(”zhangsan”,40)记录写入数据库,然后通过python manage.py shell去检查是否成功?

#urls.py
from django.conf.urls import url
from django.contrib import admin
from book import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^book/(?P<bn>\w+)/$', views.book),
    url(r'^book/(?P<a>\w+)/(?P<b>\d+)/$', views.book1),
]
# -*- coding: utf-8 -*-
from __future__ import unicode_literalsfrom django.shortcuts import render
from models import Author
# Create your views here.
def book(request,bn):
    name=request.GET.get('name')
    age=request.GET.get('age')
    if name or age:
        Author.objects.create(name=name,age=age)
    a=Author.objects.all()
    return render(request,'book_name.html',{'book_name':bn,'a':a,'name':name,'age':age})
def book1(request,a,b):
    bn='URL传参'
    if a or b:
        Author.objects.create(name=a,age=b)
    aa=Author.objects.all()
    return render(request,'book_name.html',{'book_name':bn,'a':aa,'name':a,'age':b})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>这是{{ book_name }}页面</title>
</head>
<body>
<center>
    <h1>这是{{ book_name }}页面</h1>
    {% if name or age %}
            <h1>已将记录名字:{{ name }},年龄:{{ age }}入库</h1>
    {% endif %}
    <table border="1">
    <tr>
        <th>姓名</th>
        <th>年龄</th>
    </tr>
    {% for i in a %}
            <tr>
                <td>{{ i.name }}</td>
                <td>{{ i.age }}</td>
            </tr>
    {% endfor %}
    </table>
</center>
</body>
</html>

首先是通过request的参数传参,传入name=”zhangsan”&age=40,发现入库成功!

接着是URL路由的参数传参,入库成功

python manage.py shell 查看记录,已入库成功
>>> Author.objects.all()
<QuerySet [<Author: yangfan>, <Author: Fusheng>, <Author: FF>, <Author: FF>, <Author: "zhangsan">, <Author: zhangsan>, <Author: zhangsan>, <Author: fusheng>]>

赞(0) 打赏
未经允许不得转载:http://www.yueguangzu.net逗逗网 » [Django系列]5.数据库models
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏