简介
django框架模型之数据库表增删改查基本操作
1. 生成数据库表结构
models.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom django.db import modelsclass Blog(models.Model):name = models.CharField(max_length=100)tagline = models.TextField()def __unicode__(self):return self.name
3. 增
1) 使用创建对象并save()的方法插入一条数据。
F:workSpacePythondjangoTestmodles_test>python manage.py shell
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.(InteractiveConsole)>>> from web.models import *>>> b = Blog(name='Beates Blog', tagline='All the latest Beatles news.')>>> b.save()>>>>>> b.id1L>>> b.name'Beates Blog'>>> b.tagline'All the latest Beatles news.'
2) 直接调用create方法插入一条数据不用save。
>>> Blog.objects.create(name='wangZhen Blog', tagline='All the django blog.')<Blog: wangZhen Blog>
4. 查
1) 查出库中所有条数的数据
>>> Blog.objects.all()
<QuerySet [<Blog: Beates Blog>, <Blog: wangZhen Blog>]>
2) 查询带字段名的所有条数数据
>>> Blog.objects.all().values()
<QuerySet [{'tagline': u'All the latest Beatles news.', u'id': 1L, 'name': u'Beates Blog'}, {'tagline': u'All the django blog.', u'id': 2L, 'name': u'wangZhen Blog'}]>
3) 查询单条数据
>>> Blog.objects.get(name = 'Beates Blog')<Blog: Beates Blog>
注意:如果查询的不存在时会报“DoesNotExist”的错
>>> Blog.objects.get(name = 'Beates Blogs')
Traceback (most recent call last):File "<console>", line 1, in <module>File "C:Python27libsite-packagesdjangodbmodelsmanager.py", line 85, in manager_methodreturn getattr(self.get_queryset(), name)(*args, **kwargs)File "C:Python27libsite-packagesdjangodbmodelsquery.py", line 380, in getself.model._meta.object_nameDoesNotExist: Blog matching query does not exist.
4) 查询匹配条件的多条数据
filter(name='xxx');
filter(name__contains='');
(id__in = [1,2,3]) ;
icontains(大小写无关的LIKE);
startswith和endswith,
range(SQLBETWEEN查询)
'gt', 'in', 'isnull', 'endswith', 'contains', 'lt', 'startswith', 'iendswith', 'icontains','range', 'istartswith'
eg.
>>> Blog.objects.filter(id__in = [1,2])
<QuerySet [<Blog: Beates Blog>, <Blog: wangZhen Blog>]>
>>> Blog.objects.filter(id__in = [1,2])[0]
<Blog: Beates Blog>
>>> Blog.objects.filter(id__in = [1,2])[0].name
u'Beates Blog'
>>> Blog.objects.filter(name__startswith = 'w')
<QuerySet [<Blog: wangZhen Blog>]>>>> Blog.objects.filter(tagline__contains = 'latest')<QuerySet [<Blog: Beates Blog>]>>>> Blog.objects.filter(name__icontains = 'blog')<QuerySet [<Blog: Beates Blog>, <Blog: wangZhen Blog>]>
>>> Blog.objects.filter(name__contains = 'blog')
<QuerySet []>
>>> Blog.objects.filter(id__range=(1,3))
<QuerySet [<Blog: Beates Blog>, <Blog: wangZhen Blog>]>
>>> Blog.objects.filter(id__lt = 3, name__icontains = 'wangzhen')
<QuerySet [<Blog: wangZhen Blog>]>
5) 根据字段内容排序后展示数据
根据name字段的内容进行数据排序,会根据字母和数字排序
>>> Blog.objects.order_by('name')
<QuerySet [<Blog: Beates Blog>, <Blog: wangZhen Blog>]>
6) 根据字段内容逆向排序后展示数据,加一个负号
>>> Blog.objects.order_by('-name')
<QuerySet [<Blog: wangZhen Blog>, <Blog: Beates Blog>]>
7) 连锁查询,先过滤,过滤后进行逆向排序
>>> Blog.objects.filter(id__lt = 2).order_by('-name')
<QuerySet [<Blog: Beates Blog>]>
8) 限制数据条数,相当于mysql limit
切片不支持负数,这样就数据序列倒过来的第一条,也就是最后一条数据
>>> Blog.objects.all()
<QuerySet [<Blog: Beates Blog>, <Blog: wangZhen Blog>]>>>> Blog.objects.all()[1]<Blog: wangZhen Blog>
5. 删
1) 删除表中全部数据
Blog.objects.all().delete()
2) 删除一条数据
Blog.objects.get(id = "1").delete()
3) 删除多条数据
Blog.objects.filter(id__gt = 3).delete()
6. 改
1) 修改对象属性并save进行修改
正确:
>>> a = Blog.objects.get(id=1)
>>> a.name = 'test0'>>> a.save()>>> Blog.objects.get(id = 1).name错误:u'test0‘
>>> Blog.objects.get(id = 1).name = 'test00'
>>> Blog.objects.get(id = 1).save()>>> Blog.objects.get(id = 1).nameu'test0'
2) 更新多条数据的多个字段或一个字段
>>> Blog.objects.filter(id__in=[1,2]).update(name = 'test')1L
3) 更新所有数据的多个或一个字段(慎用)(L是line的)
>>> Blog.objects.all().update(name = 'test')
2L
7. 其他
数量:
Blog.objects.all().count()
聚合:
from django.db.models import Min,Max,Sum
Blog.objects.all().aggregate(Max('guest_id'))
原始SQL:
cursor = connection.cursor()
cursor.execute('''SELECT DISTINCT first_name ROM people_person WHERE last_name = %s""", ['Lennon'])row = cursor.fetchone()