Reputation: 6302
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?
Upvotes: 0
Views: 82
Reputation: 47364
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.
Upvotes: 1