drf高级用法之——source
source的用法(三种):
1.修改前端看到字段key的值(自定义key值)
name = "三国演义" # 修改为 book_name = "三国演义"
使用代码书写:
序列化类(serializer.BookSerializer)中书写:
book_name = serializers.CharField(source='name')
2.修改前端看到的value值(同时也可以自定义key值)
name = "三国演义" # 修改为 book_name = "三国演义_sb"
使用代码书写:
models层(Book类)下书写——定义方法:
def sb_name(self): return self.name + '_sb'
序列化类(serializer.BookSerializer)中书写:
book_name = serializers.CharField(source='sb_name') # 方法名
3.关联查询
显示出版社名:
"publish_name":"xx出版社"
使用代码书写:
序列化类(serializer.BookSerializer)中书写:
publish_name = serializers.CharField(source='publish.name')