orm单表操作
1.增加數據
from app import models //方式一 book=models.Book.objects.create(name='紅樓夢',price=23.8,publish='人民出版社',author='曹雪芹',create_data='2018-09-17') //方式二 book=models.Book(name='水滸傳',price=99.8,publish='老男孩出版社',author='施耐庵',create_data='2018-08-08') book.save()2.刪除數據
from app import models //方式一 ret=models.Book.objects.filter(name='西游記').delete() //方式二 ret = models.Book.objects.filter(name='西游記').first() ret.delete()3.修改數據
ret=models.Book.objects.filter(name='西游記').update(price=20.9) #對象修改(沒有update方法,但是可以用save來修改) book = models.Book.objects.filter(name='西游記').first() book.price=89 book.save()4.查詢數據
<1> all(): 查詢所有結果
models.Book.objects.all()<2> filter(**kwargs): 它包含了與所給篩選條件相匹配的對象(與SQL語句中的where很像)
models.Book.objects.filter(name='西游記').first()<3> get(**kwargs): 返回與所給篩選條件相匹配的對象,返回結果有且只有一個,如果符合篩選條件的對象超過一個或者沒有都會拋出錯誤。
ret=models.Book.objects.get(name='紅樓夢') ret=models.Book.objects.get(id=1)<4> exclude(**kwargs): 它包含了與所給篩選條件不匹配的對象
msg = models.Book.objects.filter(name='龍珠').exists()<5> order_by(*field): 對查詢結果排序('-id')
ret=models.Book.objects.all().order_by('price').filter(name='西游記')<6> reverse(): 對查詢結果反向排序
ret=models.Book.objects.all().order_by('price'). reverse().filter(name='西游記')<7> count(): 返回數據庫中匹配查詢(QuerySet)的對象數量。
ret=models.Book.objects.all().count()<8> first(): 返回第一條記錄
msg = models.Book.objects.filter(name='三國').first()<9> last(): 返回最后一條記錄
msg = models.Book.objects.filter(name='三國').last()<10> exists(): 如果QuerySet包含數據,就返回True,否則返回False
msg = models.Book.objects.filter(name='龍珠').exists()<11> values(*field): 返回一個ValueQuerySet——一個特殊的QuerySet,運行后得到的并不是一系列model的實例化對象,而是一個可迭代的字典序列
ret=models.Book.objects.all().values('name').distinct()<12> values_list(*field): 它與values()非常相似,它返回的是一個元組序列,values返回的是一個字典序列
<13> distinct(): 從返回結果中剔除重復紀錄
5.模糊查詢數據
1.大于price__gt(查詢價格大于89 的書)
ret=models.Book.objects.filter(price__gt='89')2.小于price__lt(查詢價格小于89 的書)
ret=models.Book.objects.filter(price__lt='89')3.小于等于price__lte
ret=models.Book.objects.filter(price__lte='89')4.大于等于price__gte
ret = models.Book.objects.filter(price__gte='89')5.在某個列表中__in
ret=models.Book.objects.filter(price__in=['23.8','89','100'])6.在某個范圍中__range
ret=models.Book.objects.filter(price__range=[50,100])7.查詢名字有'紅'的書 __contains (類似于SQL中的"%紅%")
ret=models.Book.objects.filter(name__contains='紅')8.查詢名字帶p的書,忽略大小寫 __icontains
ret=models.Book.objects.filter(name__icontains='P')9.以XX開頭 __startswith
ret=models.Book.objects.filter(name__startswith='紅')10.以XX結尾 __endswith
ret=models.Book.objects.filter(name__endswith='夢')11.按年查詢 __year
ret=models.Book.objects.filter(create_data__year='2017')轉載于:https://www.cnblogs.com/jianhaozhou/p/9948913.html
總結
- 上一篇: git 修改全局配置
- 下一篇: 求环形数组的最大子数组的和