Categories
django django-rest-framework field json list

How can I define a list field in django rest framework?

Let’s say I have a class

class Tags(object):
tags = []
def __init__(self, tags):
self.tags = tags

and a custom list field

class TagsField(serializers.WritableField):
"""
Returns a list of tags, or serializes a list of tags
"""

I am not too sure where to go from here. How can I make sure that a blog post serializer defined as

class BlogPostSerializer(serializers.Serializer):
post = CharField()
tags = TagsField

would give me a json object similar to

{
"post": "Here is my blog post about python",
"tags": ["python", "django", "rest"]
}

One way to deal with arrays for a non ORM-based object is to override the to_native and from_native methods. In your case:

class TagsField(serializers.WritableField):
def from_native(self, data):
if isinstance(data, list):
return Tags(data)
else:
msg = self.error_messages['invalid']
raise ValidationError(msg)
def to_native(self, obj):
return obj.tags

If you had an ORM-based object you would like to look at the SlugRelatedField with the many = True attribute.


From Django Rest Framework version 3.0 you can also use ListField
http://www.django-rest-framework.org/api-guide/fields/#listfield