django model 类型说明:https://docs.djangoproject.com/en/1.8/ref/models/fields/
1.django model查询
1.Person.objects.raw("select * from myapp_person") # preson为model名 返回多个model实例 可以用for model in models 来提取一个实例
for p in Person.objects.raw('SELECT * FROM myapp_person'): print(p)
a =Person.objects.raw('SELECT * FROM myapp_person')[0] # index使用 会查询数据库
a = Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname]) # 参数使用
2.filter方法,相当于简单的where语句 ,返回model对象 Article.objects.filter(reporter__first_name='John')
3.get方法,相当于简单的where语句 ,返回model对象 Blog.objects.get(name="Cheddar Talk") 如果有0个或者超过一个的数据,将会报错
4.all方法,相当于select * from table,返回表中所有tuple
5.exclude方法,选择表中不满足条件的tuple q = q.exclude(body_text__icontains="food")
6.delete方法,Entry.objects.all().delete()
7.update方法 Entry.objects.filter(blog__name=‘foo‘).update(comments_on=False) 注意不能修改关联表的字段
2.创建model对象,并保存到数据库
from blog.models import Blog b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.') b.save()
3.改变model对象,并保存
b5.name = 'New name' b5.save()
4. python slice分片在其中的应用 Entry.objects.all()[:10:2]
5 order_by方法:Entry.objects.order_by('headline')[0] 或者Entry.objects.order_by('-headline')倒序
6 contains匹配 相当于like 也有忽略大小写的匹配 icontains
# Case-sensitive containment test. For example: Entry.objects.get(headline__contains='Lennon') # 注意是双下划线 # Roughly translates to this SQL: SELECT ... WHERE headline LIKE '%Lennon%';
7. 忽略大小写匹配 iexact Blog.objects.get(name__iexact="beatles blog")
8 startswith, endswith istartswith,iendswith
9 外键匹配:Entry.objects.filter(blog__name='Beatles Blog') # 选择entry object where 外键连接的表blog的name属性的值为'Beatles Blog'
10. 数据表in,gt,lt,gte,lte,range等比较操作:
# 下面3个操作是等价的 pk表示primary key
Blog.objects.get(id__exact=14) # Explicit form
Blog.objects.get(id=14) # __exact is implied
Blog.objects.get(pk=14) # pk implies id__exact
Blog.objects.get(pk=14) Blog.objects.filter(pk__in=[1,4,7]) # pk的值在1,4,7中
Blog.objects.filter(pk__gt=14) # pk的值大于14
# range 好似between and操作
import datetime
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
Entry.objects.filter(pub_date__range=(start_date, end_date))
# SQL equivalent:
SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';
11 比较不同的列
from django.db.models import F Entry.objects.filter(n_comments__gt=F('n_pingbacks')) # 选取n_comment大于n_pingbacks的tuple
12 queryset的缓存系统:当queryset被创建时cache是空的,当第一次queryset被求值时,django会将query result保存到cache中,然后接下来的有关该query result的查询操作会从cache中提取值
queryset = Entry.objects.all() print([p.headline for p in queryset]) # Evaluate the query set. print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
# 当query set取部分值时,django不会将queryset保存到cache中,从而第二次查询时,会再次查询数据库
queryset = Entry.objects.all()
print queryset[5] # Queries the database
print queryset[5] # Queries the database again
queryset = Entry.objects.all()
[entry for entry in queryset] # Queries the database
print queryset[5] # Uses cache
print queryset[5] # Uses cache
# 以下的操作会使得django将result存储到cache中
[entry for entry in queryset]
bool(queryset)
entry in queryset
list(queryset)
13. 利用Q来进行包含或与非的查询,这是对filter的一个扩展,因为filter的参数都是按照与来进行的
from django.db.models import Q Poll.objects.get( Q(question__startswith='Who'), Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)) # |表示或 )
Q(question__startswith='Who') | ~Q(pub_date__year=2005) # ~表示取反