Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"] } 
like image 464
user1876508 Avatar asked Jun 25 '13 04:06

user1876508


People also ask

What is write only field Django REST framework?

From DRF v3 onwards, setting a field as read-only or write-only can use serializer field core arguments mentioned as follows. write_only. Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.


2 Answers

There is also the ListField in django rest framework, see http://www.django-rest-framework.org/api-guide/fields/#listfield

wtih the examples:

scores = serializers.ListField(     child=serializers.IntegerField(min_value=0, max_value=100) ) 

and (other notation):

class StringListField(serializers.ListField):     child = serializers.CharField() 

this seems simpler (maybe this class is added later than the accepted anwser, but seems good to add this option anyway)

By the way, it's added since djang rest framework 3.0: http://www.django-rest-framework.org/topics/3.0-announcement/

like image 95
michel.iamit Avatar answered Oct 28 '22 21:10

michel.iamit


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

like image 41
sebastibe Avatar answered Oct 28 '22 21:10

sebastibe