Django REST Framework — is multiple nested serialization possible?

蹲街弑〆低调 提交于 2021-01-27 13:01:39

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/25252563/django-rest-framework-is-multiple-nested-serialization-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!