0

Similar to the issue found here (and maybe here)

I had the problem of having a model like so:

class Item(models.Model):
    name = models.CharField(max_length=128)
    category = models.ForeignKey(Category)

class Category(models.Model):
    name = models.CharField(max_lenght=64)

and wanting to serialize a list grouped by category like so:

[{'name': 'category 1', 'items: [ {'name': 'item1}, {'name':'item2'} ]},
 {'name': 'category 2', 'items: [ {'name': 'item3}, {'name':'item4'} ]}]
David Schumann
  • 13,380
  • 9
  • 75
  • 96

1 Answers1

0

The solution I found looks like this:

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ['name']

class ItemsSerializer(serializers.ModelSerializer):
    items = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ['name', 'items']

    def get_items(self, obj):
        items = Items.objects.filter(category=obj)  # Or do some other filtering here
        return ItemSerializer(instance=items, many=True).data

Very basic. I couldn't find this solution anywhere else though

David Schumann
  • 13,380
  • 9
  • 75
  • 96
  • Does this work? Shouldn't this be part of your question? And shouldn't the question be about why this isn't behaving like you want? – wwii Nov 04 '17 at 15:38