2018-10-04-Python全栈开发-day61-DJANGO-MODELS操作补充
生活随笔
收集整理的這篇文章主要介紹了
2018-10-04-Python全栈开发-day61-DJANGO-MODELS操作补充
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.select_related()
1. 我們基于以下模型來(lái)分析select_related的作用。class Person(models.Model);name = models.CharField(max_length=30)age = models.IntegerField()class Book(models.Model):person = models.ForeignKey(Person)title = models.CharField(max_length=50)pubtime = models.DateField()1234567892. 模型結(jié)構(gòu)為:Book - title- page- person -> ForeignKey(Person)1233. 兩種查詢(xún)方式:A. 不帶select_relatedbook = Book.objects.filter(pk=1) # 需要查詢(xún)數(shù)據(jù)庫(kù) 1 --------------------- result: book - id- title- page- Person.id --------------------- n = book.name # 需要查詢(xún)數(shù)據(jù)庫(kù) 2 a = book.age # 需要查詢(xún)數(shù)據(jù)庫(kù) 312345678910*總共向數(shù)據(jù)庫(kù)發(fā)起三次查詢(xún)。B. 帶select_relatedbook = Book.objects.select_related().filter(pk=1) # 需要查詢(xún)數(shù)據(jù)庫(kù) 1 --------------------- result: book - id- title- page- Person - id- name- age --------------------- n = book.name # 直接從book對(duì)象中取 a = book.age # 直接從book對(duì)象中取123456789101112*總共向數(shù)據(jù)庫(kù)發(fā)起一次查詢(xún)。也就是說(shuō)使用select_related()方法一次性的把Book關(guān)聯(lián)的對(duì)象都查詢(xún)出來(lái)放入對(duì)象中,再次查詢(xún)時(shí)就不需要再連接數(shù)據(jù)庫(kù),節(jié)省了后面查詢(xún)數(shù)據(jù)庫(kù)的次數(shù)和時(shí)間。---------------------本文來(lái)自 Nick_Spider 的CSDN 博客 ,全文地址請(qǐng)點(diǎn)擊:https://blog.csdn.net/weixin_39198406/article/details/78845122?utm_source=copyp=f1.objects.select_related('name).all()===得到的是f1中name外鍵對(duì)應(yīng)表的所有數(shù)據(jù),得到的是一個(gè)對(duì)象,再次從中取數(shù)據(jù)時(shí)可以直接取,減少了取值次數(shù)
?
?
2.distinct去重
f1.objects.values('name').dictinct()3.order by排序
4.extra自定制sql語(yǔ)句
## select提供簡(jiǎn)單數(shù)據(jù) # SELECT age, (age > 18) as is_adult FROM myapp_person; Person.objects.all().extra(select={'is_adult': "age > 18"}) # 加在select后面## where提供查詢(xún)條件 # SELECT * FROM myapp_person WHERE first||last ILIKE 'jeffrey%'; Person.objects.all().extra(where=["first||last ILIKE 'jeffrey%'"]) # 加一個(gè)where條件## table連接其它表 # SELECT * FROM myapp_book, myapp_person WHERE last = author_last Book.objects.all().extra(table=['myapp_person'], where=['last = author_last']) # 加from后面5.only只選取某列
f1.object,only('name')
6.defer除了某列
f1.objects.defer(''name)
7.using選擇使用的數(shù)據(jù)庫(kù)
f1.objects.all().using(default)?
補(bǔ)充操作2
queryset方法
1.dates時(shí)間
dates(self,field_name,kind,order='ASC',tzinfo='none')從數(shù)據(jù)庫(kù)中找到含有時(shí)間的字段,然后截取為固定格式kind=yesr(年),month(年-月),day(年-月-日) order =asc或者pescdatestimes(self,field_name,kind,order='ASC',tzinfo='none')可以指定轉(zhuǎn)換時(shí)間
2.aggregate只獲取某一列
3.bulk_create批量創(chuàng)建數(shù)據(jù)
4.update_or_create
修改或者創(chuàng)建
5.
轉(zhuǎn)載于:https://www.cnblogs.com/hai125698/p/9742285.html
總結(jié)
以上是生活随笔為你收集整理的2018-10-04-Python全栈开发-day61-DJANGO-MODELS操作补充的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 人和人不要靠得太近
- 下一篇: python 将元组解析为多个参数