目标:想要把image的‘image_select’字段显示出来
方法一:要使用HyperlinkedIdentityField,然而由于我把lookup_field已经占用了,就不能在修改为lookup_field =‘image_select”所以这种方法不幸’还要修改我的其它代码
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
class Meta:
model = Album
fields = ('album_name', 'artist', 'track_listing')
方法二:Nested relationships中讲解到
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ('order', 'title', 'duration')
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True, read_only=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
所以如下
class ProductDetailSerializer(serializers.ModelSerializer):
image=ImageItemsSerializer(read_only=True)
class Meta:
model = ProductDetail
fields = "__all__"
方法三:depth可以直接打开外键关系关联的对象
class ProductDetailSerializer(serializers.ModelSerializer):
class Meta:
model = ProductDetail
fields = "__all__"
depth = 1