Django涔婳RM鎿嶄綔

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django涔婳RM鎿嶄綔相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/char' title='char'>char   娣峰悎   defaults   list()   鍒涘缓   tde   min   澶嶆潅   

ORM甯哥敤鎿嶄綔

瀹樼綉鏂囨。

<1> all(): 鏌ヨ鎵€鏈夌粨鏋?QuerySet 瀵硅薄鍒楄〃 <2> get(**kwargs): 杩斿洖涓庢墍缁欑瓫閫夋潯浠剁浉鍖归厤鐨勫璞★紝杩斿洖缁撴灉鏈変笖鍙湁涓€涓紝濡傛灉绗﹀悎绛涢€夋潯浠剁殑瀵硅薄瓒呰繃涓€涓垨鑰呮病鏈夐兘浼氭姏鍑洪敊璇€? <3> filter(**kwargs): 瀹冨寘鍚簡涓庢墍缁欑瓫閫夋潯浠剁浉鍖归厤鐨勫璞? <4> exclude(**kwargs): 瀹冨寘鍚簡涓庢墍缁欑瓫閫夋潯浠朵笉鍖归厤鐨勫璞? <5> values(*field): 杩斿洖涓€涓猇alueQuerySet鈥斺€斾竴涓壒娈婄殑QuerySet锛岃繍琛屽悗寰楀埌鐨勫苟涓嶆槸涓€绯诲垪model鐨勫疄渚嬪寲瀵硅薄锛岃€屾槸涓€涓彲杩唬鐨勫瓧鍏稿簭鍒?涓嶇粰鍙傛暟鐨勮瘽杩斿洖鎵€鏈夊瓧娈靛拰鍊? <6> values_list(*field): 瀹冧笌values()闈炲父鐩镐技锛屽畠杩斿洖鐨勬槸涓€涓厓缁勫簭鍒楋紝values杩斿洖鐨勬槸涓€涓瓧鍏稿簭鍒? 涓嶇粰鍙傛暟鐨勮瘽杩斿洖鎵€鏈夊瓧娈电殑鍊? <7> order_by(*field): 瀵规煡璇㈢粨鏋滄帓搴?榛樿鍗囧簭 -闄嶅簭 <8> reverse(): 瀵规煡璇㈢粨鏋滃弽鍚戞帓搴忥紝璇锋敞鎰弐everse()閫氬父鍙兘鍦ㄥ叿鏈夊凡瀹氫箟椤哄簭鐨凲uerySet涓婅皟鐢?鍦╩odel绫荤殑Meta涓寚瀹歰rdering鎴栬皟鐢╫rder_by()鏂规硶)銆? <9> distinct(): 浠庤繑鍥炵粨鏋滀腑鍓旈櫎閲嶅绾綍(濡傛灉浣犳煡璇㈣法瓒婂涓〃锛屽彲鑳藉湪璁$畻QuerySet鏃跺緱鍒伴噸澶嶇殑缁撴灉銆傛鏃跺彲浠ヤ娇鐢╠istinct()锛屾敞鎰忓彧鏈夊湪PostgreSQL涓敮鎸佹寜瀛楁鍘婚噸銆? <10> count(): 杩斿洖鏁版嵁搴撲腑鍖归厤鏌ヨ(QuerySet)鐨勫璞℃暟閲忋€? <11> first(): 杩斿洖绗竴鏉¤褰? <12> last(): 杩斿洖鏈€鍚庝竴鏉¤褰? <13> exists(): 濡傛灉QuerySet鍖呭惈鏁版嵁锛屽氨杩斿洖True锛屽惁鍒欒繑鍥濬alse

鍒嗙被璁板繂:

鏂规硶 杩斿洖绫诲瀷
all() QuerySet瀵硅薄鍒楄〃
filter() QuerySet瀵硅薄鍒楄〃
exclude() QuerySet瀵硅薄鍒楄〃
order_by() QuerySet瀵硅薄鍒楄〃
reverse() QuerySet瀵硅薄鍒楄〃
distinct() QuerySet瀵硅薄鍒楄〃
values() QuerySet 瀛楀吀鍒楄〃
values_list() QuerySet 鍏冪粍鍒楄〃
get() 瀵硅薄
first() 瀵硅薄
last() 瀵硅薄
exists() Bool鍊?/td>

鍗曡〃鏌ヨ涔嬬濂囩殑鍙屼笅鍒掔嚎

ret = models.Person.objects.filter(pk__gt=1)  # 澶т簬 greater than
ret = models.Person.objects.filter(pk__lt=5)  # 灏忎簬 less than
ret = models.Person.objects.filter(pk__gte=1)  # 澶т簬绛変簬 greater than equal
ret = models.Person.objects.filter(pk__lte=5)  # 灏忎簬绛変簬 less than  equal

ret = models.Person.objects.filter(pk__range=[1,5])  # 鑼冨洿 鐩稿綋浜巄etween and 鍖呭惈澶村熬

ret = models.Person.objects.filter(pk__in=[1,5,7,9])  # in 鑼冨洿

ret = models.Person.objects.filter(name__contains='sun')  # like 鍖呭惈
ret = models.Person.objects.filter(name__icontains='sun')  # like ignore 蹇界暐澶у皬鍐?
ret = models.Person.objects.filter(name__startswith='a')  # 浠ヤ粈涔堝紑澶?ret = models.Person.objects.filter(name__istartswith='a')  # 浠ヤ粈涔堝紑澶?ignore 蹇界暐澶у皬鍐?
ret = models.Person.objects.filter(name__endswith='x')  # 浠ヤ粈涔堢粨灏?ret = models.Person.objects. filter(name__iendswith='a')  # 浠ヤ粈涔堢粨灏?ignore 蹇界暐澶у皬鍐?
ret = models.Person.objects.filter(birth__year='2020')
ret = models.Person.objects.filter(birth__contains='2020-10')

ret = models.Person.objects.filter(age__isnull=False)  # 涓簄ull鍜?#39;'绌哄瓧绗︿覆涓嶄竴鏍?/code>

Foreign Key鎿嶄綔

姝e悜鏌ユ壘

瀵硅薄鏌ユ壘

璇硶锛?/p>

瀵硅薄.鍏宠仈瀛楁.瀛楁

绀轰緥锛?/p>

book_obj = models.Book.objects.first()  # 绗竴鏈功瀵硅薄
print(book_obj.publisher)  # 寰楀埌杩欐湰涔﹀叧鑱旂殑鍑虹増绀惧璞?print(book_obj.publisher_id)  # 澶栭敭瀛楁鐨刬d
print(book_obj.publisher.name)  # 寰楀埌鍑虹増绀惧璞$殑鍚嶇О

瀛楁鏌ユ壘

璇硶锛?/p>

**鍏宠仈瀛楁__瀛楁**

绀轰緥锛?/p>

print(models.Book.objects.filter(publisher__name__contains='娌?#39;))

# 鎸囧畾related_query_name鏃?浼樺厛绾ф渶楂?# 鏌ヨ鎵€鏈夊嚭鐗堢ぞ鐨勫悕瀛椾腑鍖呭惈"娌?quot;鐨勫嚭鐗堢ぞ鎵€鍑虹増鐨勪功绫?# 杞寲涓簊ql璇彞: 杩炶〃鍚?瀵筽ublisher__name杩涜绛涢€?鐒跺悗灞曠ず涔︾睄淇℃伅

鍙嶅悜鎿嶄綔

瀵硅薄鏌ユ壘

璇硶锛?/p>

obj.琛ㄥ悕_set

绀轰緥锛?/p>

publisher_obj = models.Publisher.objects.first()  # 鎵惧埌绗竴涓嚭鐗堢ぞ瀵硅薄
obj = publisher_obj.book_set         # 鍏崇郴绠$悊瀵硅薄(涓€瀵瑰鏃?
books = publisher_obj.book_set.all()  # 鎵惧埌绗竴涓嚭鐗堢ぞ鍑虹増鐨勬墍鏈変功
titles = books.values_list("title")  # 鎵惧埌绗竴涓嚭鐗堢ぞ鍑虹増鐨勬墍鏈変功鐨勪功鍚?# 涓嶆寚瀹歳elated_name鏃?绫诲悕灏忓啓_set
# 璁剧疆related_name='books': publisher_obj.books.all()     

瀛楁鏌ユ壘

璇硶锛?/p>

**琛ㄥ悕__瀛楁**

绀轰緥锛?/p>

print(models.Publisher.objects.filter(book__title__contains='瀛?#39;))
# 鎵惧埌鎵€鏈変功鍚嶄腑鍖呭惈"瀛?quot;鐨勪功绫嶇殑鍑虹増绀?/code>

Many To Many Field

"鍏宠仈绠$悊鍣?quot;鏄湪涓€瀵瑰鎴栬€呭瀵瑰鐨勫叧鑱斾笂涓嬫枃涓娇鐢ㄧ殑绠$悊鍣ㄣ€?/p>

瀹冨瓨鍦ㄤ簬涓嬮潰涓ょ鎯呭喌锛?/p>

  1. 澶栭敭鍏崇郴鐨勫弽鍚戞煡璇?/li>
  2. 澶氬澶氬叧鑱斿叧绯?/li>

绠€鍗曟潵璇村氨鏄綋 鐐瑰悗闈㈢殑瀵硅薄 鍙兘瀛樺湪澶氫釜鐨勬椂鍊欏氨鍙互浣跨敤浠ヤ笅鐨勬柟娉曘€?/p>

瀵硅薄鏌ユ壘

# 姝e悜
book_obj = models.Book.objects.get(pk=1)
print(book_obj.author)         # 鍏崇郴绠$悊瀵硅薄
print(book_obj.author.all())   # 姣忎竴涓璞?
# 鍙嶅悜
author_obj = models.Author.objects.get(pk=1)
print(author_obj.book_set)     # 鍏崇郴绠$悊瀵硅薄
print(author_obj.book_set.all())  # 姣忎竴涓璞?/code>

瀛楁鏌ユ壘

# 姝e悜
print(models.Book.objects.filter(author__age__gt=10))

# 鍙嶅悜
print(models.Author.objects.filter(book__title='鎮熺┖浼?#39;))

鏂规硶

all()

鑾峰彇鎵€鏈夊璞?Query set

book_obj = models.Book.objects.get(pk=1)
print(book_obj.author.all())
author_obj = models.Author.objects.get(pk=1)
print(author_obj.book_set.all())

set()

璁剧疆澶氬澶氬叧绯?鍙互鏀緄d鍒楄〃,涔熷彲浠ユ斁瀵硅薄鍒楄〃

book_obj.author.set([1, 3])   # id鐨勫垪琛?
book_obj.author.set(models.Author.objects.filter(pk__in=[2, 3]))   # 瀵硅薄鍒楄〃

# 鍒犻櫎涔嬪墠鐨勮褰?閲嶆柊娣诲姞,涓嶆槸淇敼

add()

娣诲姞澶氬澶氬叧绯?鍙互鏀緄d,涔熷彲浠ユ斁瀵硅薄,娉ㄦ剰涓嶆槸鍒楄〃

book_obj.author.add(1, 4)   # id

book_obj.author.add(*models.Author.objects.filter(pk__in=[1, 2, 3, 4]))    # 鐢?灏嗗璞″垪琛ㄦ墦鏁f垚鍗曚釜瀵硅薄

remove()

浠庡叧鑱斿璞¢泦涓Щ闄ゆ墽琛岀殑model瀵硅薄,鐢ㄦ硶鍚宎dd()

book_obj = models.Book.objects.first()
book_obj.authors.remove(2, 3)
book_obj.authors.remove(*models.Author.objects.filter(pk__in=[1, 2, 3, 4]))

clear()

浠庡叧鑱斿璞¢泦涓Щ闄や竴鍒囧璞°€?/p>

book_obj = models.Book.objects.first()
book_obj.authors.clear()

create()

鍒涘缓涓€涓柊鐨勫璞★紝淇濆瓨瀵硅薄锛屽苟灏嗗畠娣诲姞鍒板叧鑱斿璞¢泦涔嬩腑锛岃繑鍥炴柊鍒涘缓鐨勫璞°€?/p>

book_obj = models.Book.objects.get(pk=1)
obj = book_obj.author.create(name='鐚叓鎴?#39;, age=20, phone='12345678912')

娉ㄦ剰锛?/strong>

瀵逛簬Foreign Key瀵硅薄:

  • clear()鍜宺emove()鏂规硶浠呭湪null=True鏃跺瓨鍦?/li>
  • set()鍜宎dd()鍙兘娣诲姞瀵硅薄
  • create()鏃?鍙互鍙︽寚瀹氬閿叧鑱斿璞?/li>

涓句釜渚嬪瓙锛?/strong>

Foreign Key瀛楁娌¤缃畁ull=True鏃讹紝

class Book(models.Model):
    title = models.CharField(max_length=32)
    publisher = models.ForeignKey(to=Publisher)

娌℃湁clear()鍜宺emove()鏂规硶锛?/p>

>>> models.Publisher.objects.first().book_set.clear()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'RelatedManager' object has no attribute 'clear'

褰揊oreign Key瀛楁璁剧疆null=True鏃讹紝

class Book(models.Model):
    name = models.CharField(max_length=32)
    publisher = models.ForeignKey(to=Class, null=True)

姝ゆ椂灏辨湁clear()鍜宺emove()鏂规硶锛?/p>

models.Publisher.objects.first().book_set.clear()

娉ㄦ剰锛?/p>

瀵逛簬鎵€鏈夌被鍨嬬殑鍏宠仈瀛楁锛宎dd()銆乧reate()銆乺emove()鍜宑lear(),set()閮戒細椹笂鏇存柊鏁版嵁搴撱€傛崲鍙ヨ瘽璇达紝鍦ㄥ叧鑱旂殑浠讳綍涓€绔紝閮戒笉闇€瑕佸啀璋冪敤save()鏂规硶銆?/p>

鑱氬悎

aggregate()鏄?code>QuerySet 鐨勪竴涓粓姝㈠瓙鍙ワ紝鎰忔€濇槸璇达紝瀹冭繑鍥炰竴涓寘鍚竴浜涢敭鍊煎鐨勫瓧鍏搞€?/p>

閿殑鍚嶇О鏄仛鍚堝€肩殑鏍囪瘑绗︼紝鍊兼槸璁$畻鍑烘潵鐨勮仛鍚堝€笺€傞敭鐨勫悕绉版槸鎸夌収瀛楁鍜岃仛鍚堝嚱鏁扮殑鍚嶇О鑷姩鐢熸垚鍑烘潵鐨勩€?/p>

鐢ㄥ埌鐨勫唴缃嚱鏁帮細

from django.db.models import Avg, Sum, Max, Min, Count

绀轰緥锛?/p>

models.Book.objects.aggregate(Max('price'))
# 'price__max': Decimal('39.99')
# 鏌ヨ鎵€鏈変功涓渶楂樼殑浠锋牸

濡傛灉鎯宠涓鸿仛鍚堝€兼寚瀹氫竴涓悕绉帮紝鍙互鍚戣仛鍚堝瓙鍙ユ彁渚涘畠銆?/p>

models.Book.objects.aggregate(max=Max('price'))
# 'max': Decimal('39.99')

濡傛灉甯屾湜鐢熸垚涓嶆涓€涓仛鍚堬紝浣犲彲浠ュ悜aggregate()瀛愬彞涓坊鍔犲彟涓€涓弬鏁般€傛墍浠ワ紝濡傛灉浣犱篃鎯崇煡閬撴墍鏈夊浘涔︿环鏍肩殑鏈€澶у€煎拰鏈€灏忓€硷紝鍙互杩欐牱鏌ヨ锛?/p>

models.Book.objects.aggregate(max=Max('price'), min=Min('price'), avg=Avg('price'))
# 'max': Decimal('39.99'), 'min': Decimal('0.99'), 'avg': 15.9675

鍒嗙粍

鍏堝涔犱竴涓婼QL璇彞鐨勫垎缁勩€?/p>

鍋囪鐜板湪鏈変竴寮犲叕鍙歌亴鍛樿〃锛?/p>

鎶€鏈浘鐗? src=

浣跨敤鍘熺敓SQL璇彞锛屾寜鐓ч儴闂ㄥ垎缁勬眰骞冲潎宸ヨ祫锛?/p>

select dept,AVG(salary) from employee group by dept;

ORM鏌ヨ:

娉ㄦ剰: annotate鏄敞閲?灏卞儚鏄湪鍘熻〃鍚庢柊鍔犱簡涓€鍒?/p>

models.Employee.objects.values("dept").annotate(avg=Avg("salary")
# 鎸夌収"dept"杩涜鍒嗙粍,鐒跺悗鏌ヨ"dept"鍜屾瘡缁勭殑Avg("salary")

杩炶〃鏌ヨ鐨勫垎缁勶細

鎶€鏈浘鐗? src=

SQL鏌ヨ锛?/p>

select dept.name,AVG(salary) from employee inner join dept on (employee.dept_id=dept.id) group by dept_id;

ORM鏌ヨ锛?/p>

models.Dept.objects.annotate(avg=Avg("employee__salary")).values("name", "avg")
# Dept left join employee, 鎸夌収dept.id杩涜鍒嗙粍, 缁欐瘡缁勫姞涓婁竴涓柊瀛楁avg=Avg("employee__salary"), 鐒跺悗鎷垮嚭姣忕粍鐨?quot;name", "avg"

鏇村绀轰緥锛?/h3>

绀轰緥1锛氱粺璁℃瘡涓€鏈功鐨勪綔鑰呬釜鏁?/p>

print(models.Book.objects.annotate(count=Count('author__name')).values('title', 'count'))

绀轰緥2锛氱粺璁″嚭姣忎釜鍑虹増绀剧殑鏈€渚垮疁鐨勪功鐨勪环鏍?/p>

鏂规硶涓€:

print(models.Publisher.objects.annotate(min=Min('book__price')).values('name', 'min'))
# Publisher left join book,鎸夌収Publisher.id杩涜鍒嗙粍,鐒跺悗鎷垮嚭姣忕粍鐨勫嚭鐗堢ぞ鍚嶅瓧鍜屾渶灏忕殑涔︾睄浠锋牸

鏂规硶浜?

print(models.Book.objects.values('publisher__name').annotate(min=Min('price')))
# book left join Publisher,鎸夌収publisher.name杩涜鍒嗙粍,鐒跺悗鎷垮嚭publisher.name鍜屾渶灏忕殑涔︾睄浠锋牸

绀轰緥3锛氱粺璁′笉姝竴涓綔鑰呯殑鍥句功

print(models.Book.objects.annotate(count=Count('author__name')).filter(count__gt=1).values('title', 'count'))

绀轰緥4锛氭牴鎹竴鏈浘涔︿綔鑰呮暟閲忕殑澶氬皯瀵规煡璇㈤泦 QuerySet杩涜鎺掑簭

print(models.Book.objects.annotate(count=Count('author__id')).order_by('count').values('title', 'count'))

绀轰緥5锛氭煡璇㈠悇涓綔鑰呭嚭鐨勪功鐨勬€讳环鏍?/p>

print(models.Author.objects.annotate(sum=Sum('book__price')).values('name', 'sum'))

F鏌ヨ鍜孮鏌ヨ

F鏌ヨ

鍦ㄤ笂闈㈡墍鏈夌殑渚嬪瓙涓紝鎴戜滑鏋勯€犵殑杩囨护鍣ㄩ兘鍙槸灏嗗瓧娈靛€间笌鏌愪釜甯搁噺鍋氭瘮杈冦€傚鏋滄垜浠瀵逛袱涓瓧娈电殑鍊煎仛姣旇緝锛岄偅璇ユ€庝箞鍋氬憿锛?/p>

Django 鎻愪緵 F() 鏉ュ仛杩欐牱鐨勬瘮杈冦€侳() 鐨勫疄渚嬪彲浠ュ湪鏌ヨ涓紩鐢ㄥ瓧娈碉紝鏉ユ瘮杈冨悓涓€涓?model 瀹炰緥涓袱涓笉鍚屽瓧娈电殑鍊笺€?/p>

绀轰緥1锛?/p>

鏌ヨ璇勮鏁板ぇ浜庢敹钘忔暟鐨勪功绫?/p>

from django.db.models import F
models.Book.objects.filter(comment__gt=F('collect'))

Django 鏀寔 F() 瀵硅薄涔嬮棿浠ュ強 F() 瀵硅薄鍜屽父鏁颁箣闂寸殑鍔犲噺涔橀櫎鍜屽彇妯$殑鎿嶄綔銆?/p>

models.Book.objects.filter(comment__gt=F('collect') + 2)

淇敼鎿嶄綔涔熷彲浠ヤ娇鐢‵鍑芥暟,姣斿灏嗘瘡涓€鏈功鐨勪环鏍兼彁楂?0鍏?/p>

models.Book.objects.update(price=F('price') + 30)

寮曠敵锛?/strong>

濡傛灉瑕佷慨鏀筩har瀛楁鍜嬪姙锛?/p>

濡傦細鎶婃墍鏈変功鍚嶅悗闈㈠姞涓?绗竴鐗?

from django.db.models.functions import Concat
from django.db.models import Value
models.Book.objects.update(title=Concat(F("title"), Value("("), Value("绗竴鐗?quot;), Value(")")))

Q鏌ヨ

filter() 绛夋柟娉曚腑鐨勫叧閿瓧鍙傛暟鏌ヨ閮芥槸涓€璧疯繘琛?code>and鐨勩€?濡傛灉闇€瑕佹墽琛屾洿澶嶆潅鐨勬煡璇紙渚嬪or璇彞锛夛紝鍙互浣跨敤Q瀵硅薄銆?/p>

绀轰緥1锛?/p>

鏌ヨ浣滆€呭悕鏄皬浠欏コ鎴栧皬榄斿コ鐨勪功绫?

models.Book.objects.filter(Q(authors__name="灏忎粰濂?quot;)|Q(authors__name="灏忛瓟濂?quot;))

鍙互缁勫悎& 鍜?code>| 鎿嶄綔绗︿互鍙婁娇鐢ㄦ嫭鍙疯繘琛屽垎缁勬潵缂栧啓浠绘剰澶嶆潅鐨?code>Q 瀵硅薄銆傚悓鏃讹紝Q 瀵硅薄鍙互浣跨敤~ 鎿嶄綔绗﹀彇鍙嶏紝杩欏厑璁哥粍鍚堟甯哥殑鏌ヨ鍜屽彇鍙?NOT) 鏌ヨ銆?/p>

绀轰緥锛氭煡璇綔鑰呭悕瀛楁槸灏忎粰濂冲苟涓斾笉鏄?018骞村嚭鐗堢殑涔︾殑涔﹀悕銆?/p>

models.Book.objects.filter(Q(author__name="灏忎粰濂?quot;) & ~Q(publish_date__year=2018)).values_list("title")

鏌ヨ鍑芥暟鍙互娣峰悎浣跨敤Q 瀵硅薄鍜屽叧閿瓧鍙傛暟銆傛墍鏈夋彁渚涚粰鏌ヨ鍑芥暟鐨勫弬鏁帮紙鍏抽敭瀛楀弬鏁版垨Q 瀵硅薄锛夐兘灏?quot;AND鈥濆湪涓€璧枫€備絾鏄紝濡傛灉鍑虹幇Q 瀵硅薄锛屽畠蹇呴』浣嶄簬鎵€鏈夊叧閿瓧鍙傛暟鐨勫墠闈€?/p>

渚嬪锛氭煡璇㈠嚭鐗堝勾浠芥槸2017鎴?018锛屼功鍚嶄腑甯︾墿璇殑鎵€鏈変功銆?/p>

models.Book.objects.filter(Q(publish_date__year=2018) | Q(publish_date__year=2017), title__icontains="鐗╄")

浜嬪姟

import os

if __name__ == '__main__':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ORM.settings")
    import django
    django.setup()

    import datetime
    from app01 import models

    try:
        from django.db import transaction
        with transaction.atomic():
            new_publisher = models.Publisher.objects.create(name="鐏槦鍑虹増绀?quot;)
            models.Book.objects.create(title="姗樺瓙鐗╄", publish_date=datetime.date.today(), publisher_id=10)  # 鎸囧畾涓€涓笉瀛樺湪鐨勫嚭鐗堢ぞid
    except Exception as e:
        print(str(e))

Django ORM鎵ц鍘熺敓SQL

# extra
# 鍦≦uerySet鐨勫熀纭€涓婄户缁墽琛屽瓙璇彞
# extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)

# select鍜宻elect_params鏄竴缁勶紝where鍜宲arams鏄竴缁勶紝tables鐢ㄦ潵璁剧疆from鍝釜琛?# Entry.objects.extra(select='new_id': "select col from sometable where othercol > %s", select_params=(1,))
# Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
# Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
# Entry.objects.extra(select='new_id': "select id from tb where id > %s", select_params=(1,), order_by=['-nid'])

涓句釜渚嬪瓙锛?models.UserInfo.objects.extra(
                    select='newid':'select count(1) from app01_usertype where id>%s',
                    select_params=[1,],
                    where = ['age>%s'],
                    params=[18,],
                    order_by=['-age'],
                    tables=['app01_usertype']
                )
                """
                select 
                    app01_userinfo.id,
                    (select count(1) from app01_usertype where id>1) as newid
                from app01_userinfo,app01_usertype
                where 
                    app01_userinfo.age > 18
                order by 
                    app01_userinfo.age desc
                """


# 鎵ц鍘熺敓SQL
# 鏇撮珮鐏垫椿搴︾殑鏂瑰紡鎵ц鍘熺敓SQL璇彞
# from django.db import connection, connections
# cursor = connection.cursor()  # cursor = connections['default'].cursor()
# cursor.execute("""SELECT * from auth_user where id = %s""", [1])
# row = cursor.fetchone()

Query Set鏂规硶澶у叏

##################################################################
# PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #
##################################################################

def all(self)
    # 鑾峰彇鎵€鏈夌殑鏁版嵁瀵硅薄

def filter(self, *args, **kwargs)
    # 鏉′欢鏌ヨ
    # 鏉′欢鍙互鏄細鍙傛暟锛屽瓧鍏革紝Q

def exclude(self, *args, **kwargs)
    # 鏉′欢鏌ヨ
    # 鏉′欢鍙互鏄細鍙傛暟锛屽瓧鍏革紝Q

def select_related(self, *fields)
    鎬ц兘鐩稿叧锛氳〃涔嬮棿杩涜join杩炶〃鎿嶄綔锛屼竴娆℃€ц幏鍙栧叧鑱旂殑鏁版嵁銆?
    鎬荤粨锛?    1. select_related涓昏閽堜竴瀵逛竴鍜屽瀵逛竴鍏崇郴杩涜浼樺寲銆?    2. select_related浣跨敤SQL鐨凧OIN璇彞杩涜浼樺寲锛岄€氳繃鍑忓皯SQL鏌ヨ鐨勬鏁版潵杩涜浼樺寲銆佹彁楂樻€ц兘銆?
def prefetch_related(self, *lookups)
    鎬ц兘鐩稿叧锛氬琛ㄨ繛琛ㄦ搷浣滄椂閫熷害浼氭參锛屼娇鐢ㄥ叾鎵ц澶氭SQL鏌ヨ鍦≒ython浠g爜涓疄鐜拌繛琛ㄦ搷浣溿€?
    鎬荤粨锛?    1. 瀵逛簬澶氬澶氬瓧娈碉紙ManyToManyField锛夊拰涓€瀵瑰瀛楁锛屽彲浠ヤ娇鐢╬refetch_related()鏉ヨ繘琛屼紭鍖栥€?    2. prefetch_related()鐨勪紭鍖栨柟寮忔槸鍒嗗埆鏌ヨ姣忎釜琛紝鐒跺悗鐢≒ython澶勭悊浠栦滑涔嬮棿鐨勫叧绯汇€?
def annotate(self, *args, **kwargs)
    # 鐢ㄤ簬瀹炵幇鑱氬悎group by鏌ヨ

    from django.db.models import Count, Avg, Max, Min, Sum

    v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id'))
    # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id

    v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id')).filter(uid__gt=1)
    # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

    v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id',distinct=True)).filter(uid__gt=1)
    # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

def distinct(self, *field_names)
    # 鐢ㄤ簬distinct鍘婚噸
    models.UserInfo.objects.values('nid').distinct()
    # select distinct nid from userinfo

    娉細鍙湁鍦≒ostgreSQL涓墠鑳戒娇鐢╠istinct杩涜鍘婚噸

def order_by(self, *field_names)
    # 鐢ㄤ簬鎺掑簭
    models.UserInfo.objects.all().order_by('-id','age')

def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
    # 鏋勯€犻澶栫殑鏌ヨ鏉′欢鎴栬€呮槧灏勶紝濡傦細瀛愭煡璇?
    Entry.objects.extra(select='new_id': "select col from sometable where othercol > %s", select_params=(1,))
    Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
    Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
    Entry.objects.extra(select='new_id': "select id from tb where id > %s", select_params=(1,), order_by=['-nid'])

 def reverse(self):
    # 鍊掑簭
    models.UserInfo.objects.all().order_by('-nid').reverse()
    # 娉細濡傛灉瀛樺湪order_by锛宺everse鍒欐槸鍊掑簭锛屽鏋滃涓帓搴忓垯涓€涓€鍊掑簭


 def defer(self, *fields):
    models.UserInfo.objects.defer('username','id')
    鎴?    models.UserInfo.objects.filter(...).defer('username','id')
    #鏄犲皠涓帓闄ゆ煇鍒楁暟鎹?
 def only(self, *fields):
    #浠呭彇鏌愪釜琛ㄤ腑鐨勬暟鎹?     models.UserInfo.objects.only('username','id')
     鎴?     models.UserInfo.objects.filter(...).only('username','id')

 def using(self, alias):
     鎸囧畾浣跨敤鐨勬暟鎹簱锛屽弬鏁颁负鍒悕锛坰etting涓殑璁剧疆锛?

##################################################
# PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #
##################################################

def raw(self, raw_query, params=None, translations=None, using=None):
    # 鎵ц鍘熺敓SQL
    models.UserInfo.objects.raw('select * from userinfo')

    # 濡傛灉SQL鏄叾浠栬〃鏃讹紝蹇呴』灏嗗悕瀛楄缃负褰撳墠UserInfo瀵硅薄鐨勪富閿垪鍚?    models.UserInfo.objects.raw('select id as nid from 鍏朵粬琛?#39;)

    # 涓哄師鐢烻QL璁剧疆鍙傛暟
    models.UserInfo.objects.raw('select id as nid from userinfo where nid>%s', params=[12,])

    # 灏嗚幏鍙栫殑鍒板垪鍚嶈浆鎹负鎸囧畾鍒楀悕
    name_map = 'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'
    Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)

    # 鎸囧畾鏁版嵁搴?    models.UserInfo.objects.raw('select * from userinfo', using="default")

    ################### 鍘熺敓SQL ###################
    from django.db import connection, connections
    cursor = connection.cursor()  # cursor = connections['default'].cursor()
    cursor.execute("""SELECT * from auth_user where id = %s""", [1])
    row = cursor.fetchone() # fetchall()/fetchmany(..)


def values(self, *fields):
    # 鑾峰彇姣忚鏁版嵁涓哄瓧鍏告牸寮?
def values_list(self, *fields, **kwargs):
    # 鑾峰彇姣忚鏁版嵁涓哄厓绁?
def dates(self, field_name, kind, order='ASC'):
    # 鏍规嵁鏃堕棿杩涜鏌愪竴閮ㄥ垎杩涜鍘婚噸鏌ユ壘骞舵埅鍙栨寚瀹氬唴瀹?    # kind鍙兘鏄細"year"锛堝勾锛? "month"锛堝勾-鏈堬級, "day"锛堝勾-鏈?鏃ワ級
    # order鍙兘鏄細"ASC"  "DESC"
    # 骞惰幏鍙栬浆鎹㈠悗鐨勬椂闂?        - year : 骞?01-01
        - month: 骞?鏈?01
        - day  : 骞?鏈?鏃?
    models.DatePlus.objects.dates('ctime','day','DESC')

def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
    # 鏍规嵁鏃堕棿杩涜鏌愪竴閮ㄥ垎杩涜鍘婚噸鏌ユ壘骞舵埅鍙栨寚瀹氬唴瀹癸紝灏嗘椂闂磋浆鎹负鎸囧畾鏃跺尯鏃堕棿
    # kind鍙兘鏄?"year", "month", "day", "hour", "minute", "second"
    # order鍙兘鏄細"ASC"  "DESC"
    # tzinfo鏃跺尯瀵硅薄
    models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.UTC)
    models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.timezone('Asia/Shanghai'))

    """
    pip3 install pytz
    import pytz
    pytz.all_timezones
    pytz.timezone(鈥楢sia/Shanghai鈥?
    """

def none(self):
    # 绌篞uerySet瀵硅薄


####################################
# METHODS THAT DO DATABASE QUERIES #
####################################

def aggregate(self, *args, **kwargs):
   # 鑱氬悎鍑芥暟锛岃幏鍙栧瓧鍏哥被鍨嬭仛鍚堢粨鏋?   from django.db.models import Count, Avg, Max, Min, Sum
   result = models.UserInfo.objects.aggregate(k=Count('u_id', distinct=True), n=Count('nid'))
   ===> 'k': 3, 'n': 4

def count(self):
   # 鑾峰彇涓暟

def get(self, *args, **kwargs):
   # 鑾峰彇鍗曚釜瀵硅薄

def create(self, **kwargs):
   # 鍒涘缓瀵硅薄

def bulk_create(self, objs, batch_size=None):
    # 鎵归噺鎻掑叆
    # batch_size琛ㄧず涓€娆℃彃鍏ョ殑涓暟
    objs = [
        models.DDD(name='r11'),
        models.DDD(name='r22')
    ]
    models.DDD.objects.bulk_create(objs, 10)

def get_or_create(self, defaults=None, **kwargs):
    # 濡傛灉瀛樺湪锛屽垯鑾峰彇锛屽惁鍒欙紝鍒涘缓
    # defaults 鎸囧畾鍒涘缓鏃讹紝鍏朵粬瀛楁鐨勫€?    obj, created = models.UserInfo.objects.get_or_create(username='root1', defaults='email': '1111111','u_id': 2, 't_id': 2)

def update_or_create(self, defaults=None, **kwargs):
    # 濡傛灉瀛樺湪锛屽垯鏇存柊锛屽惁鍒欙紝鍒涘缓
    # defaults 鎸囧畾鍒涘缓鏃舵垨鏇存柊鏃剁殑鍏朵粬瀛楁
    obj, created = models.UserInfo.objects.update_or_create(username='root1', defaults='email': '1111111','u_id': 2, 't_id': 1)

def first(self):
   # 鑾峰彇绗竴涓?
def last(self):
   # 鑾峰彇鏈€鍚庝竴涓?
def in_bulk(self, id_list=None):
   # 鏍规嵁涓婚敭ID杩涜鏌ユ壘
   id_list = [11,21,31]
   models.DDD.objects.in_bulk(id_list)

def delete(self):
   # 鍒犻櫎

def update(self, **kwargs):
    # 鏇存柊

def exists(self):
   # 鏄惁鏈夌粨鏋?/code>

Django缁堢鎵撳嵃SQL璇彞

鍦―jango椤圭洰鐨剆ettings.py鏂囦欢涓紝鍦ㄦ渶鍚庡鍒剁矘璐村涓嬩唬鐮侊細

LOGGING = 
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': 
        'console':
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        ,
    ,
    'loggers': 
        'django.db.backends': 
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        ,
    

鍗充负Django椤圭洰閰嶇疆涓婁竴涓悕涓?code>django.db.backends鐨刲ogger瀹炰緥鍗冲彲鏌ョ湅缈昏瘧鍚庣殑SQL璇彞銆?/p>

鍦≒ython鑴氭湰涓皟鐢―jango鐜

import os

if __name__ == '__main__':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ORM.settings")
    import django
    django.setup()

    from app01 import models

    books = models.Book.objects.all()
    print(books)

以上是关于Django涔婳RM鎿嶄綔的主要内容,如果未能解决你的问题,请参考以下文章

Django涔婱odel鎿嶄綔

Java鎿嶄綔JSON鏁版嵁--Gson鎿嶄綔JSON鏁版嵁

鎿嶄綔绯荤粺-鎿嶄綔绯荤粺-鍐呮牳涓殑灞忓箷鎵撳嵃(涓?

鏁版嵁搴撶瑪璁?馃搾 MySQL鍩虹鎿嶄綔鍛戒护 鍒嗙被娓呮櫚

鑺傜偣鎿嶄綔

pandas 鎿嶄綔-2

(c)2006-2024 SYSTEM All Rights Reserved IT常识