赞
踩
用法:MyModel.objects.all()
作用:查询MyModel实例中的所有数据
相当于 select * from table;
返回:QuerySet
from bookstore.models import Book
books=Book.objects.all()
for book in books:
print(book.title,book.pub)
用法:MyModel.objects.values()
作用:查询MyModel实例中的部分列
相当于 select a,b from table;
返回:QuerySet 内字典
from bookstore.models import Book
books=Book.objects.values()
for book in books:
print(book['title'],book['pub'])
用法:MyModel.objects.values_list()
作用:查询MyModel实例中的部分列
相当于 select a,b from table;
返回:QuerySet 内元组
from bookstore.models import Book
books=Book.objects.values_list()
for book in books:
print(book['title'],book['pub'])
用法:MyModel.objects.order_by("列","列")
作用:查询MyModel实例中的所有数据,并按照所给的列进行排序
说明:默认升序,倒序 order_by("-列","-列")
返回:QuerySet
from bookstore.models import Book
books=Book.objects.order_by('pub')
for book in books:
print(book.title,book.pub)
可以拼接使用,例如MyModel.objects.values().order_by("列","列")
print(books.query)可以得到sql语句
用法:MyModel.objects.filter(条件1,条件2)
作用:查询MyModel实例中的符合条件的数据值
说明:条件1:a=b,键值对形式
多个条件一起为and关系
返回:QuerySet
from bookstore.models import Book
books=Book.objects.filter(pub="清华大学出版社")
for book in books:
print(book.title,book.pub)
用法:MyModel.objects.exclude(条件1,条件2)
作用:查询MyModel实例中的不符合条件的数据值
说明:条件1:a=b,键值对形式
多个条件一起为and关系
返回:QuerySet
from bookstore.models import Book
books=Book.objects.exclude(pub="清华大学出版社")
for book in books:
print(book.title,book.pub)
用法:MyModel.objects.get(条件1,条件2)
作用:查询MyModel实例中的符合条件的 一条 数据
说明:条件1:a=b,键值对形式
多个条件一起为and关系
数据查询多余一条报错 MultipleObjectsReturned
数据查询少余一条报错 DoesNotExist
返回:object
from bookstore.models import Book
book=Book.objects.get(pub="清华大学出版社")
print(book.title,book.pub)
from django.db.models import Q,F
Q(条件1) | Q(条件2)
Q(条件1) & Q(条件2)
Q(条件1) & ~Q(条件2)
Book.objects.all().update(market_price=F('market_price')+10)
book = Book.objects.filter(market_price__gt = F('price'))
导入 from django.db.models import *
函数 Sum , Avg , Count , Max , Min
语法 MyModel.objects.aggregate(结果变量名=聚合函数("列"))
返回结果:{结果变量名:值}
#结果变量名自定义
QuerySet.annotate(结果变量名=聚合函数("列"))
返回结果:QuerySet
⑴不建议,易被sql注入
语法 MyModel.objects.raw(sql语句)
返回值 RawQuerySet(只支持基础操作,比如循环)
防范
MyModel.objects.raw(sql语句,拼接参数)
MyModel.objects.raw(select * from table where ID=%s,[str])
⑵
from django.db import connection
whith connection.cursor() as cur:
cur.execute(sql语句,拼接参数)
查询谓词(适用于(filter,exclude,get))
用法:MyModel.objects.filter(id__exact=1)
相当于 select * from table where id =1;
用法:MyModel.objects.filter(name__contains="w")
相当于 select * from table where name like "%w%";
MyModel.objects.filter(name__icontains=“w”)
忽略大小写
相当于 select * from table where name like "w%";
相当于 select * from table where name like "%w";
用法:MyModel.objects.filter(id__gt=1)
相当于 select * from table where id > 1;
用法:MyModel.objects.filter(id__in=[1,4,8])
相当于 select * from table where id in (1,4,8);
用法:MyModel.objects.filter(id__range = (2,9))
相当于 select * from table where id between 2 and 9;
from bookstore.models import Book
book1 = Book(name='runoob')
book1.save()
# 另外一种方式
# book1 = Book.objects.create(name='runoob')
# 批量增加数据
# create_list = []
# book1 = Book(name='runoob1')
# create_list.append(book1)
# book2 = Book(name='runoob2')
# create_list.append(book2)
# Book.objects.bulk_create(create_list)
# 修改或创建
# Book.objects.update_or_create(name='runoob1',defaults={"name":"runoob1"})
from bookstore.models import Book
book1 = Book.objects.get(id=1)
book1.name = 'Google'
book1.save()
# 另外一种方式
# Book.objects.filter(id=1).update(name='Google')
# 修改所有的列
# Book.objects.all().update(name='Google')
(数据库一般不删除数据而是把is_delete列设为True)
test1 = Test.objects.get(id=1)
test1.delete()
# 另外一种方式
# Book.objects.filter(id=1).delete()
# 删除所有数据
# Book.objects.all().delete()
(注合并后count()计数出错,可
len([i.id for i in alarms_query_set])进行计数)
queryset = queryset1.union(queryset2)
数据库版本低可能连接多个Queryset会报错
queryset = list(queryset1) + list(queryset2)
会返回一个list列表可正常进行序列化操作
A.objects.values_list("id",'name').filter(data__is_valid=1).distinct()
A.objects.filter(is_valid=1).annotate(id=F("B__id")).values("id")
res = cookbook.objects.raw('select id as nid from epos_cookbook where id>%s', params=[1, ])
print(res.columns) # ['nid']
print(type(res)) # <class 'django.db.models.query.rawqueryset'>
# 在select里面查询到的数据orm里面的要一一对应
res = cookbook.objects.raw("select * from epos_cookbook")
print(res)
for i in res:
print(i.create_date)
print(i)
res = cookbook.objects.raw('select * from epos_cookbook where id>%s', params=[1, ])
# 后面可以加参数进来
print(res)
for i in res:
# print(i.create_date)
print(i)
# select age, (age > 18) as is_adult from myapp_person;
person.objects.all().extra(select={'is_adult': "age > 18"}) # 加在select后面
## where提供查询条件
# select * from myapp_person where first||last ilike 'jeffrey%';
person.objects.all().extra(where=["first||last ilike 'jeffrey%'"]) # 加一个where条件
## table连接其它表
# select * from myapp_book, myapp_person where last = author_last
book.objects.all().extra(table=['myapp_person'], where=['last = author_last']) # 加from后面
## params添参数
# !! 错误的方式 !!
first_name = 'joe' # 如果first_name中有sql特定字符就会出现漏洞
person.objects.all().extra(where=["first = '%s'" % first_name])
# 正确方式
person.objects.all().extra(where=["first = '%s'"], params=[first_name])
from django.db import connection
cursor=connection.cursor()
# 如果需要配置数据库
# cursor=connection['default'].cursor()
cursor.execute('select * from test')
ret=cursor.fetchall()
print(ret)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。