ORM正向和反向查詢

2022-01-13 01:23:23 字數 2933 閱讀 2824

表結構

from django.db import models

# create your models here.

class publisher(models.model):

id = models.autofield(primary_key=true)

name = models.charfield(max_length=32)

class book(models.model):

id = models.autofield(primary_key=true)

name = models.charfield(max_length=32)

publisher = models.foreignkey('publisher', related_name='person_book', related_query_name='ooxx')

插入資料

# book表

id title pubtime person_id

1 書1 1533225600000 1

2 書2 1533225600000 1

3 書3 1534435200000 1

4 書4 1535644800000 2

5 書5 1535126400000 3

# publisher表

id name

1 出版社1

2 出版社2

3 出版社3

正向查詢: 外來鍵所在表去查另一張表,book >> publisher

反向查詢:普通表去查外來鍵所在的表,publisher >> book

正向查詢,基於物件跨表查詢

book_obj = models.book.objects.all()  # 取到書籍物件

book_obj.publisher.name # 書籍的出版社名字,html

book_obj.person.id # 書籍的出版社id,html

跨表查詢,利用雙下劃線跨表查詢

models.book.objects.filter(id=1).values('

publisher__name

') # 查詢id是1的書的出版社的名字,一條雙下劃線就是跨一張表

models.book.objects.filter(id=1).values_list('publisher__name')

反向查詢

物件查詢  obj.表名_set()

publisher_obj =models.publisher.objects.first()  # 找到第乙個出版社物件

ret =publisher_obj.book_set.all() # 找到第乙個出版社出版的所有數

for i in

ret: # 迴圈物件

print(i.name) # 列印出每乙個書的書名

publisher_obj = models.publisher.objects.first()  #

找到第乙個出版社物件

books = publisher_obj.book_set.all() #

找到第乙個出版社出版的所有書

titles = books.values_list("

name

") #

找到第乙個出版社出版的所有書的書名

print(titles)

因為使用了releted_name,就是用person_book代替了表字段名字

表字段person = models.foreignkey(person, related_name='person_book')

所以這一這樣寫

books = publisher_obj.person_book.all()

titles = books.values_list('name')

print(titles)

如果表字段person = models.foreignkey(person, related_name='person_book',related_query_name="xxoo")

related_query_name="xxoo",這裡表示跨表查詢xxoo代替表的名字book

books = publisher_obj.ooxx_set.all()

基於雙下劃線

ret = models.publisher.objects.filter(id=1).values_list('person_book__name')

person_book是通過releted_name給對應關係起的名字,通過person_book就找到了關聯的表,再通過雙下劃線找到name

print(ret)

附帶django裡面指令碼的**

import

osif

__name__ == '

__main__':

#載入django專案的配置資訊

os.environ.setdefault("

django_settings_module

", "

專案名.settings")

#匯入django,並啟動django專案

import

django

django.setup()

models

# 查詢id為1的出版社出版的所有書的name

ret = models.publisher.objects.filter(id=1).values_list('

person_book__name')

print(ret)

ORM正向和反向查詢

表結構 from django.db import models create your models here.class publisher models.model id models.autofield primary key true name models.charfield max l...

ORM正向和反向查詢

表結構 from django.db import models class publisher models.model id models.autofield primary key true name models.charfield max length 32 class book mode...

序列化 正向查詢 和反向查詢

課程標籤 class coursetag base title models.charfield 課程標籤 max length 32 sequence models.integerfield 展示順序 default 10 class meta db table tb coursetag def ...