1

I have a django model as follows:

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')

and i have serializers as follows:

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

The B serializer works as follows:

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

What do i have to tweak to make it result as follows:

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

1 Answer 1

1

Change your CSerializer as follows:

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

    class Meta:
        model = C
Sign up to request clarification or add additional context in comments.

4 Comments

but this is a foreign key relation which is the same what i am already doing. I am trying the reverse relation in the second one
@RogerFederer Have you tested my code? It produces the result what you showed as required output in your question.
oh i am so sorry! i forgot to remove the many=True, and read_only....it is working...thank you
I'm glad that it helped :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.