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

后端 未结 3 606
北荒
北荒 2020-12-29 02:56

Let\'s say I have a class

class Tags(object):

    tags = []

    def __init__(self, tags):
        self.tags = tags

and a custom list fiel

相关标签:
3条回答
  • 2020-12-29 03:30

    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/

    0 讨论(0)
  • 2020-12-29 03:32

    If you are using Postgesql, you can use an ArrayField

    0 讨论(0)
  • 2020-12-29 03:33

    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

    0 讨论(0)
提交回复
热议问题