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

2022-08-24 18:15:08 字數 942 閱讀 7701

# 普通字段

name= models.charfield(max_lenth=20)

​# 一對多欄位,foreignkey

name= models.foreignkey(tablename, on_delete="", related_name=none)

​# 多對多字段,manytomanyfield()

name= models.manytomanyfield(tablename, )

# 正向查詢:主表直接查詢關聯表內容

在serializers.charfield欄位中,新增source引數, 格式為source = '外來鍵.某欄位'

course_name = serializers.charfield(source='course.title',required=false)

# 反向查詢:關聯表通過外來鍵查詢主表內容

​class chaptersserializer(serializers.modelserializer):

# 正向查詢,找到課程表

# course_name = serializers.charfield(source='course.title',required=false)

# 反向查詢,找到節表對應的資訊

sections = sectionsserializer(many=true)

class meta:

fields = '__all__'

model = models.chapters

class sectionsserializer(serializers.modelserializer):

class meta:

fields = '__all__'

model = models.sections​​

​​​​

​​

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

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

序列化正反向查詢

序列化 正向查詢 from rest framework import serializers from users.models import userinfo 正向查詢 class userinfoserializer serializers.serializer 類名小寫.外來鍵字段 good...

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...