0

I have two django models as shown

model 1

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

model2

class Small(models.Model):
    name = models.CharField(max_length=50, null=True, blank=True)
    address = models.CharField(max_length=200, null=True, blank=True)
    big = models.ForeignKey(Big, related_name='small',null=True,on_delete=models.CASCADE)

There can be more than one Small items inside a Big item. The Bigserializer looks like below

class BigSerializer(serializers.ModelSerializer):

class Meta:
    model = Hotel
    fields = ('name','small')

Now on accessing the Big items,i am getting name and small fields. But the small field returns only the id of the Small model. I need the whole details like name and address of Small item inside the small field. How could i achieve it?

1 Answer 1

1

You need to define Small serializer class:

class SmallSerializer(serializers.ModelSerializer):

    class Meta:
        model = Small
        fields = ('name','address')

and use this serializer in BigSerializer class:

class BigSerializer(serializers.ModelSerializer):
    small = SmallSerializer(many=True, read_only=True)

    class Meta:
        model = Hotel
        fields = ('name','small')

See details here.

Note that if you need writable nested serialization, you should implement custom create and update methods inside BigSerializer, see section writable nested serialization.

Sign up to request clarification or add additional context in comments.

Comments

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.