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
在母表中,得到子表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": [ "内衣一号", "内衣二号" ] }