3

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 Answer 1

4

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.

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

1 Comment

Thanks. This was my problem -- turns out I had the related_name set on only one of the classes in my model definition.

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.