Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework -- is multiple nested serialization possible?

I would like to do something like the following:

models.py

class Container(models.Model):
    size  = models.CharField(max_length=20)
    shape = models.CharField(max_length=20)

class Item(models.Model):
    container = models.ForeignKey(Container)
    name  = models.CharField(max_length=20)
    color = models.CharField(max_length=20)

class ItemSetting(models.Model):
    item = models.ForeignKey(Item)
    attribute_one = models.CharField(max_length=20)
    attribute_two = models.CharField(max_length=20)

serializers.py

class ItemSettingSerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemSetting


class ItemSerializer(serializers.ModelSerializer):
    settings = ItemSettingSerializer(many=True)

    class Meta:
        model = Item
        fields = ('name', 'color', 'settings')


class ContainerSerializer(serializers.ModelSerializer):
    items = ItemSerializer(many=True)

    class Meta:
        model = Container
        fields = ('size', 'shape', 'items')

When I do nesting of only one level (Container and Item) it works for me. But when I try to add another level of nesting with the ItemSetting, it throws an AttributeError and complains 'Item' object has no attribute 'settings'

What am I doing wrong?

like image 249
tadasajon Avatar asked Apr 25 '26 23:04

tadasajon


1 Answers

Multiple nested serialization works for me. The only major difference is that I specify a related_name for the FK relationships. So try doing this:

class Item(models.Model):
    container = models.ForeignKey(Container, related_name='items')

class ItemSetting(models.Model):
    item = models.ForeignKey(Item, related_name='settings')

Hope this works for you.

like image 174
AdelaN Avatar answered Apr 28 '26 11:04

AdelaN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!