用多对一关系序列化模型中的字段

时间:2019-03-27 02:59:44

标签: django django-rest-framework

我有一个帖子模型和一个图像模型,如下所示:

class PropertyPost(models.Model):
    ....


class Image(models.Model):
    prop_post = models.ForeignKey(
        PropertyPost,
        related_name='images4thisproperty',
        on_delete=models.CASCADE)

,这是它们相关的序列化:

class PropPostSerializer(serializers.HyperlinkedModelSerializer):
 images4thisproperty = serializers.HyperlinkedRelatedField(
        many=True,
        read_only=True,
        view_name='image-detail')
      class Meta:
        model = PropertyPost
        fields = (...,images4thisproperty,...)



class ImageSerializer(serializers.HyperlinkedModelSerializer):
    prop_post = serializers.SlugRelatedField(queryset=PropertyPost.objects.all(),
                                             slug_field='pk')
      class Meta:
        model = Image
        fields = (
            'url',
            'photo',
            'prop_post',
        )

现在当我序列化对象时,对于propertypost模型,输出json如下所示:

{
            "images4thisproperty": [
                "http://139.50.80.132/images/4",
                "http://139.50.80.132/images/3"
            ],
 }

对于图像模型如下所示:

{
    "url": "http://139.50.80.132/images/1",
    "photo": "http://139.50.80.132/media/myposts/2019/20190327004444_8e3f5152-a3fd-40f2-857b-e16db3900fee.png",
    "prop_post": 1,
},
{
    "url": "http://139.50.80.132/images/2",
    "photo": "http://139.50.80.132/media/myposts/2019/20190327004450_659c207a-f3e1-471e-b2b0-c33c4708494a.png",
    "prop_post": 1,
},

我想知道我是否也可以在我的propertypost中将Image模型的 photo 字段序列化。换句话说,我想在我的propertypost序列化程序输出中使用它:

{
            "images4thisproperty": [
                "http://139.50.80.132/images/4",
                "http://139.50.80.132/images/3"
            ],
            "photo": [
                "http://139.50.80.132/media/myposts/2019/20190327004444_8e3f5152-a3fd-40f2-857b-e16db3900fee.png",
                "http://139.50.80.132/media/myposts/2019/20190327004450_659c207a-f3e1-471e-b2b0-c33c4708494a.png",
            ]

 }

请让我知道我该怎么做, 谢谢,

1 个答案:

答案 0 :(得分:0)

尝试修改PropSerializer

class PropPostSerializer(serializers.HyperlinkedModelSerializer):
    images4thisproperty = ImageSerializer(
        many=True,
        read_only=True,
        view_name='image-detail')
    class Meta:
        model = PropertyPost
        fields = (...,images4thisproperty,...)