如何在django rest框架中定义列表字段? [英] How can I define a list field in django rest framework?
问题描述
让我说一堂课
class Tags(object):
tags = []
def __init__(self, tags):
self.tags = tags
和自定义列表字段
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
会给我一个类似于
{
"post": "Here is my blog post about python",
"tags": ["python", "django", "rest"]
}
推荐答案
为基于非ORM的对象处理数组的一种方法是重写to_native
和from_native
方法.就您而言:
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
如果您有一个基于ORM的对象,则希望查看具有many = True
属性的SlugRelatedField
.
If you had an ORM-based object you would like to look at the SlugRelatedField
with the many = True
attribute.
从Django Rest Framework 3.0版开始,您还可以使用ListField http://www.django-rest-framework.org/api- guide/fields/#listfield
From Django Rest Framework version 3.0 you can also use ListField http://www.django-rest-framework.org/api-guide/fields/#listfield
这篇关于如何在django rest框架中定义列表字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!