简体   繁体   中英

how can I serializer a list in django-rest-framework?

I want to serializer a object list,
I try this:

serializers/task_list.py

from rest_framework import serializers

class TaskListSerializer(serializers.Serializer):
>---id = serializers.CharField()
>---user_id = serializers.CharField()  

then I give serializer a dict, It works:

from task_list import TaskListSerializer as ts
result = ts({'id':1, 'user_id': 2})    
print result.data
{'user_id': u'1', 'id': u'1'}

it good for dict,

now I want to serializer a list, like this:

result = ts([{'id':1, 'user_id': 1}])
print result.data

it give me a error:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/var/data/users/chenc3/opt/websoc/lib/python2.6/site-packages/rest_framework/serializers.py", line 487, in data
    ret = super(Serializer, self).data
  File "/var/data/users/chenc3/opt/websoc/lib/python2.6/site-packages/rest_framework/serializers.py", line 223, in data
    self._data = self.to_representation(self.instance)
  File "/var/data/users/chenc3/opt/websoc/lib/python2.6/site-packages/rest_framework/serializers.py", line 447, in to_representation
    attribute = field.get_attribute(instance)
  File "/var/data/users/chenc3/opt/websoc/lib/python2.6/site-packages/rest_framework/fields.py", line 418, in get_attribute
    raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `id` on serializer `TaskListSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `list` instance.
Original exception text was: 'list' object has no attribute 'id'.  

how can I fixed it?

you need to add many=True like:

result = ts([{'id':1, 'user_id': 1}], many=True)
print result.data

Learn more here

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