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'} ]}]

1 Answer 1

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

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

1 Comment

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?

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.