Note that there are some explanatory texts on larger screens.

plurals
  1. POSerializing a list of object as dictionnary in DjangoRestFramework
    text
    copied!<p>Using django &amp; django-rest-framework, I have the following model (this is simplified but it's all there):</p> <pre><code>class Device(Model): #stuff class DeviceInformation(Model): device = ForeignKey(Device, reverse='infos') key = CharField(max_length=32) value = CharField(max_length=1024) </code></pre> <p>When serializing a device through django-rest-framework's ModelSerializer, I get something like this:</p> <pre><code>{ //stuff infos: [{ 'key':'BatteryLevel', 'value':'80%' },{ 'key':'DeviceName', 'value':'my device' }, //etc ] } </code></pre> <p>Which is perfectly normal. However, it would make much more sense to serialize into something like this:</p> <pre><code>{ //stuff infos: { 'BatteryLevel':'80%', 'DeviceName':'my device', //etc } } </code></pre> <p>How do I do that? Is it even possible? Note that I don't need to deserialize any of these information.</p> <p>EDIT: my serializers are as follows:</p> <pre><code>class DeviceInfoSerializer(ModelSerializer): class Meta: model = DeviceInformation fields = ('key', 'value') read_only_fields = fields class DeviceSerializer(HyperlinkedModelSerializer): udid = serializers.CharField(read_only=True) def __init__(self, *args, **kwargs): super(DeviceSerializer, self).__init__(*args, **kwargs) if hasattr(self, 'object') and self.object and not self.many: self.data['infos'] = DeviceInfoSerializer( self.object.infos.all(), many=True).data class Meta: model = Device fields = ['udid', 'model', 'tracked'] read_only_fields = ('model', 'tracked') slug_field = 'udid' </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload