序列化正反向查詢

2022-07-09 14:27:12 字數 2684 閱讀 3930

序列化(正向查詢)

from rest_framework import serializers

from users.models import userinfo

## 正向查詢

class userinfoserializer(serializers.serializer):

# 類名小寫.外來鍵字段

goods = serializers.charfield(source='goods.type_name',required=false) # 顯示一對多欄位名稱

class meta:

model = userinfo

# 路徑

class pathserializer(serializers.modelserializer):

class meta:

model = path

fields = '__all__'

class jieduanserializer(serializers.modelserializer):

courses = courseserializer(many=true)

class meta:

model = jieduan

fields = '__all__'

class pathdeepserializer(serializers.modelserializer):

jieduan = jieduanserializer(many=true)

class meta:

model = path

fields = '__all__'

''' 一對多序列化(反向查詢)'''

class usertypeserializer(serializers.serializer):

type_name = serializers.charfield()

# 法1一對多關聯物件序列化:此字段將被序列化為關聯物件的主鍵

userinfo_set = serializers.primarykeyrelatedfield(read_only=true, many=true)

# 法2一對多關聯物件序列化:此字段將被序列化為關聯物件的字串表示方式(即__str__方法的返回值)

# userinfo_set = serializers.stringrelatedfield(read_only=true,many=true)

# 法3一對多關聯物件序列化:使用關聯物件的序列化器

# userinfo_set = userinfoserializer(many=true)

from rest_framework import serializers

from users.models import userinfo

## 正向查詢

class userinfoserializer(serializers.serializer):

# 類名小寫.外來鍵字段

goods = serializers.charfield(source='goods.type_name',required=false) # 顯示一對多欄位名稱

class meta:

model = userinfo

# 路徑

class pathserializer(serializers.modelserializer):

class meta:

model = path

fields = '__all__'

class jieduanserializer(serializers.modelserializer):

courses = courseserializer(many=true)

class meta:

model = jieduan

fields = '__all__'

class pathdeepserializer(serializers.modelserializer):

jieduan = jieduanserializer(many=true)

class meta:

model = path

fields = '__all__'

''' 一對多序列化(反向查詢)'''

class usertypeserializer(serializers.serializer):

type_name = serializers.charfield()

# 法1一對多關聯物件序列化:此字段將被序列化為關聯物件的主鍵

userinfo_set = serializers.primarykeyrelatedfield(read_only=true, many=true)

# 法2一對多關聯物件序列化:此字段將被序列化為關聯物件的字串表示方式(即__str__方法的返回值)

# userinfo_set = serializers.stringrelatedfield(read_only=true,many=true)

# 法3一對多關聯物件序列化:使用關聯物件的序列化器

# userinfo_set = userinfoserializer(many=true)

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

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

django正反向查詢

django正反向查詢 當我們的表存在外來鍵想要從一找多的時候該怎麼查詢,當我們從多找一的時候又應該怎麼查詢.一找多首先我們要建立乙個專案,在專案的model.py中建立兩個模型.from django.db import models class usertype models.model tit...

正反向 多表查詢

正向 反向外來鍵字段在我手上那麼,我查你就是正向 外來鍵字段如果不在手上,我查你就是反向 book 外來鍵字段在書那兒 正向 publish publish 外來鍵字段在書那兒 反向 book 一對一和多對多正反向的判斷也是如此 正向查詢按欄位 反向查詢按表名小寫 set 1.查詢書籍主鍵為1的出版...