继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Django rest framework展示模型关系

无无法师
关注TA
已关注
手记 44
粉丝 54
获赞 130

目标:想要把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 
打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP