Drf 序列化 ModelSerializer跨表取数据
1、对于OneToOne、Foreignkey、choices字段可以使用source取出相关信息:
class CourseSerializer(serializers.ModelSerializer):
# choices字段
degree = serializers.CharField(source='get_degree_display')
# ForeignKey字段
teacher = serializers.CharField(source='teacher.name')
class Meta:
model = Course
fields = '__all__'
2、对于ManyToMany字段,例如:
class BookSerializers(serializers.ModelSerializer):
authors = serializers.SerializerMethodField()
publisher = serializers.CharField(source='publisher.title')
class Meta:
model = Book
fields = "__all__" # 可选择显示字段
# exclude = ['price',] # 排除字段
def get_authors(self,obj):
query_set = obj.authors.all()
return [{'name':obj.name} for obj in query_set]
{
"id": 2,
"authors": [
{
"name": "蒋勋"
}
],
"publisher": "长江出版社",
"title": "蒋勋说唐诗",
"pub_date": "2018-11-04",
"word_count": 12,
"price": 34
}