简体   繁体   中英

Django: How to serialize QuerySet into object instead of array?

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 Day s 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM