1

我有一个 django 模型如下:

class A(models.Model):
    comments = models.CharField(max_length=200, blank=True)

class B(models.Model):
    name = models.CharField(max_length=50, blank=True)

class c(models.Model):
    a = models.ForeignKey(A, related_name='modelA')
    b = models.ForeignKey(B, related_name='modelB')

我有如下序列化程序:

class ASerializer(serializers.ModelSerializer):

    class Meta:
        model = A

class CSerializer(serializers.ModelSerializer):

    class Meta:
        model = C

class BSerializer(serializers.ModelSerializer):
    modelB = CSerializer(many=True, read_only=True)

    class Meta:
        model = B

B 序列化器的工作原理如下:

[
    {
        "id": 2,
        "modelB": [
            {
                "id": 1,
                "b": 2,
                "a": 3
            }
        ]
    }
]

我必须进行什么调整才能使其结果如下:

[
    {
        "id": 2,
        "modelB": [
            {
                "id": 1,
                "b": 2,
                "a": [
                     {
                         "id": 1,
                         "comments": "",
                     }
                 ]
            }
        ]
    }
]
4

1 回答 1

1

更改您的CSerializer如下:

class CSerializer(serializers.ModelSerializer):
    a = ASerializer()

    class Meta:
        model = C
于 2015-09-12T14:10:44.597 回答