https://www.django-rest-framework.org/api-guide/relations/

在编程中核心的就是数据结构。

关系字段用来表示model之间的关系,比如外键,m2m,o2o,还有反转关系,自定义关系-GenericForeignKey

关系字段申明在relations.py中,在使用的时候,可以在自己的序列化类中使用serializers.<FieldName>来引用。

使用ModelSerializers类的时候,会自动生成序列化字段和关系,我们可以检查这些自动生成的字段,然后来决定如何自定义关系样式。

(venv) E:\Python\dj_test>python manage.py shell
>>> from xxx.serializers import ClothesSerializer
>>> serializer = ClothesSerializer()
>>> print(repr(serializer))
ClothesSerializer():
url = HyperlinkedIdentityField(view_name='clothes-detail')
id = IntegerField(label='ID', read_only=True)
color = SlugRelatedField(queryset=<QuerySet [<Colors: instance:yellow>, <Colors: instance:red>]>, slug_field='colors_cn')
desc = CharField(max_length=64)
#使用shell,导入序列化类,然后实例化,然后使用repr函数打印这个实例的对象关系

  

API Reference

为了解释多个类型的关系字段,这里使用几个例子。我们的模型将用于音乐专辑Album,以及每张专辑中列出的曲目Track。

StringRelatedField

在这个案例中,可以查看使用yellow颜色作为外键的clothes有哪些,这个clothes字段在这里是read only。

它的作用是得到关联表model.__str__方法的返回字段。因为对应的子表是to-many关系,所以要加上many=True

class ColorsSerializer(serializers.ModelSerializer):
clothes = serializers.StringRelatedField(many=True) class Meta:
model = Colors
fields = ('url', 'id', 'colors', 'clothes')
--->
{
"url": "http://127.0.0.1:8002/colors/1/",
"id": 1,
"colors": "yellow",
"clothes": [
"内衣一号",
"内衣二号"
]
}

Arguments:

  • many - If applied to a to-many relationship, you should set this argument to True

  

PrimaryKeyRelatedField

它的作用是得到关联表的主键。

class ColorsSerializer(serializers.ModelSerializer):
clothes = serializers.PrimaryKeyRelatedField(queryset=Colors.objects.all(),many=True) class Meta:
model = Colors
fields = ('url', 'id', 'colors', 'clothes')
--->
{
"url": "http://127.0.0.1:8002/colors/1/",
"id": 1,
"colors": "yellow",
"clothes": [
1,
2
]
}

  

By default this field is read-write, although you can change this behavior using the read_only flag.

Arguments:

  • queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
  • many - If applied to a to-many relationship, you should set this argument to True.
  • allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.
  • pk_field - Set to a field to control serialization/deserialization of the primary key's value. For example, pk_field=UUIDField(format='hex') would serialize a UUID primary key into its compact hex representation.

HyperlinkedRelatedField

它的作用是得到关联表的url

class ColorsSerializer(serializers.ModelSerializer):
clothes = serializers.HyperlinkedRelatedField(queryset=Colors.objects.all(),many=True,view_name='clothes-detail') class Meta:
model = Colors
fields = ('url', 'id', 'colors', 'clothes')
--->
{
"url": "http://127.0.0.1:8002/colors/1/",
"id": 1,
"colors": "yellow",
"clothes": [
"http://127.0.0.1:8002/clothes/1/",
"http://127.0.0.1:8002/clothes/2/"
]
}

  

By default this field is read-write, although you can change this behavior using the read_only flag.


Note: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the lookup_field and lookup_url_kwarg arguments.

This is suitable for URLs that contain a single primary key or slug argument as part of the URL.

If you require more complex hyperlinked representation you'll need to customize the field, as described in the custom hyperlinked fields section, below.


Arguments:

  • view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format <modelname>-detailrequired.
  • queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
  • many - If applied to a to-many relationship, you should set this argument to True.
  • allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.
  • lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk'.
  • lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field.
  • format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument.

SlugRelatedField

它的作用是得到关联表的具体某个字段

# Clothes的color是外键,默认情况下,color字段会对应母表的主键,id。
# 使用SlugRelatedField可以指向外键,slug_field表示获取哪个字段返回给color
# 这里color这个属性就被重写了
class ClothesSerializer(serializers.ModelSerializer):
color = serializers.SlugRelatedField(queryset=Colors.objects.all(), slug_field='colors')
class Meta:
model = Clothes
fields = ('url', 'id', 'color', 'desc')
--->
{
"url": "http://127.0.0.1:8002/clothes/5/",
"id": 5,
"color": "red",
"desc": "袜子三号"
}

 

By default this field is read-write, although you can change this behavior using the read_only flag.

When using SlugRelatedField as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with unique=True.

Arguments:

  • slug_field - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, usernamerequired
  • queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
  • many - If applied to a to-many relationship, you should set this argument to True.
  • allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.

HyperlinkedIdentityField

和HyperlinkedModelSerializer上的url字段一个作用

 

Nested relationships

class ColorsSerializer(serializers.ModelSerializer):
# 序列化嵌套
clothes = ClothesSerializer(many=True, read_only=True) class Meta:
model = Colors
fields = ('url', 'id', 'colors', 'clothes')
--->
{
"url": "http://127.0.0.1:8002/colors/1/",
"id": 1,
"colors": "yellow",
"clothes": [
{
"url": "http://127.0.0.1:8002/clothes/1/",
"id": 1,
"color": "yellow",
"desc": "内衣三号"
},
{
"url": "http://127.0.0.1:8002/clothes/2/",
"id": 2,
"color": "yellow",
"desc": "内衣二号"
}
]
}
#被嵌套的关联表,整个出现在母表的字段中

  

Writable nested serializers

默认情况下,嵌套序列化程序是只读的。如果要支持对嵌套序列化程序字段的写操作,则需要创建create()和/或update()方法,以便明确指定应如何保存子关系。

class ColorsSerializer(serializers.ModelSerializer):
# 序列化嵌套
clothes = ClothesSerializer(many=True) class Meta:
model = Colors
fields = ('url', 'id', 'colors', 'clothes') def create(self, validated_data):
clothes_data = validated_data.pop('clothes') #先把clothes字段弹出来
colors = Colors.objects.create(**validated_data) #然后colors实例落表
for clothe_data in clothes_data: #clothes_data是多个实例
Clothes.objects.create(color=colors,**clothe_data) #把每个clothe实例落表,其中外键color指向color实例
return colors

  

DRF教程10-关系字段的更多相关文章

  1. 黑马lavarel教程---10、lavarel模型关联

    黑马lavarel教程---10.lavarel模型关联 一.总结 一句话总结: 1.模型关联比较方便,一次定义,后面都可以使用 2.关联关系 使用动态属性进行调用 1.一对多,多对多实例? 一对多: ...

  2. 无废话ExtJs 入门教程九[数字字段:NumberField、隐藏字段Hidden、日期字段:DataFiedl]

    无废话ExtJs 入门教程九[数字字段:NumberField.隐藏字段Hidden.日期字段:DataFiedl] extjs技术交流,欢迎加群(201926085) 继上第六节内容,我们在表单里加 ...

  3. 【译】ASP.NET MVC 5 教程 - 10:添加验证

    原文:[译]ASP.NET MVC 5 教程 - 10:添加验证 在本节中,我们将为Movie模型添加验证逻辑,并确认验证规则在用户试图使用程序创建和编辑电影时有效. DRY 原则 ASP.NET M ...

  4. Linux pwn入门教程(10)——针对函数重定位流程的几种攻击

    作者:Tangerine@SAINTSEC 本系列的最后一篇 感谢各位看客的支持 感谢原作者的付出一直以来都有读者向笔者咨询教程系列问题,奈何该系列并非笔者所写[笔者仅为代发]且笔者功底薄弱,故无法解 ...

  5. [译]Vulkan教程(10)交换链

    [译]Vulkan教程(10)交换链 Vulkan does not have the concept of a "default framebuffer", hence it r ...

  6. Django框架之第六篇(模型层)--单表查询和必知必会13条、单表查询之双下划线、Django ORM常用字段和参数、关系字段

    单表查询 补充一个知识点:在models.py建表是 create_time = models.DateField() 关键字参数: 1.auto_now:每次操作数据,都会自动刷新当前操作的时间 2 ...

  7. python 之 Django框架(ORM常用字段和字段参数、关系字段和和字段参数)

    12.324 Django ORM常用字段 .id = models.AutoField(primary_key=True):int自增列,必须填入参数 primary_key=True.当model ...

  8. Directx11教程(10) 画一个简易坐标轴

    原文:Directx11教程(10) 画一个简易坐标轴       本篇教程中,我们将在三维场景中,画一个简易的坐标轴,分别用红.绿.蓝三种颜色表示x,y,z轴的正向坐标轴. 为此,我们要先建立一个A ...

  9. 06 ORM常用字段 关系字段 数据库优化查询

    一.Django ORM 常用字段和参数 1.常用字段 models中所有的字段类型其实本质就那几种,整形varchar什么的,都没有实际的约束作用,虽然在models中没有任何限制作用,但是还是要分 ...

随机推荐

  1. CSS相关(2)

    特效:       2D:              平移:可以为负值,单位px transform:translateX(200px) translateY(200px); 简写:transform ...

  2. 使用input:file控件在微信内置浏览器上传文件返回未显示选择的文件

    使用input:file控件在微信内置浏览器上传文件返回未显示选择的文件 原来的写法: <input type="file" accept="image/x-png ...

  3. Logback的AsyncAppender与RollingFileAppender流程解析

    近期工作中涉及到文件记录.文件翻转等操作,思考有没有成熟的代码以便参考. 因此,第一时间就联想到Logback的AsyncAppender以及RollingFileAppender. AsyncApp ...

  4. 题解 loj2065 「SDOI2016」模式字符串

    点分治. 考虑经过当前分治中心\(u\)的点对数量. 这种数点对数的问题,有一个套路.我们可以依次考虑\(u\)的每个儿子,看用当前的儿子,能和之前已经考虑过的所有儿子,组成多少点对.这样所有合法的点 ...

  5. 利用pandas,处理每天的点名。。

    学以致用,,最近的疫情,导致每天都要向学校汇报班上同学的情况,可是每次提交的人总是慢半拍,为了快速找出谁还没有提交检查表,利用最近学的知识,快速检查提交名单.方便你我他. 上代码: import pa ...

  6. println 与 print区别

    ------------恢复内容开始------------ println 与 print区别: 1.print输出之后不换行,如下: public class Newstart {    publ ...

  7. python重要函数eval

    1.参数会作为一个 Python 表达式(从技术上说是一个条件列表)被解析并求值 >>> x = 1 >>> eval('x+1') 2 2.去除字符串两边的引号 ...

  8. 055、Java中使用for循环输出乘法口诀表

    01.代码如下: package TIANPAN; /** * 此处为文档注释 * * @author 田攀 微信382477247 */ public class TestDemo { public ...

  9. Hive 中的 order by, sort by, distribute by 与 cluster by

    Order By order by 会对输入做全排序, 因此只有一个Reducer(多个Reducer无法保证全局有序), 然而只有一个Reducer, 会导致当输入规模较大时, 消耗较长的计算时间. ...

  10. yolov3测试自己的数据

    yolov3测试自己的数据 前言 上一篇我已经介绍了利用yolov3预训练权重文件(只包含卷积层)并训练 只需要进行如下编译: ./darknet detector train cfg/voc.dat ...