0

I want to serialize a QuerySet into a JSON object instead of JSON array.

For model Day, the serialized QuerySet should be an object with Day.date keys and serialized Days as values.

class DaySerializer(serializers.ModelSerializer):
    class Meta:
        model = Day
        exclude = []

This returns an array of serialized objects:

DaySerializer(Day.objects.all(),many=True).data

{'15.02.2005':{...},
 '16.02.2005':{...},
  ...
}

I'm curious if there is some DRF way to do that.

1
  • from where these dates are coming? Commented May 3, 2019 at 4:00

1 Answer 1

1

AFAIK there is not an out-of-the-box way of doing that, but you can override .to_representation() and .to_internal_value() methods of the serializer to achieve that.

These methods enable you to alter how both serialization and de-serialization is done.

See here for details.

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

3 Comments

I dont think this would help. Because to_representation() is only handling one object at a time.
Did you try it? I suspect incoming instance would be a list of objects if many=True.
Yes.. The many=True magic is being carried out somewhere else.

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.