GET和POST在Django REST框架Serializer中的比较性质 [英] Assymetric nature of GET and POST in a Django REST framework Serializer
问题描述
我试图制作允许GET和POST的模型和序列化程序
I am trying to make models and serializers that allow GET and POST
GET将允许客户端查看所有用户的列表,并将显示信息名字,姓氏等,但不是access_token
The GET will allow the client to see a list of all Users, and will show info like first name, last name, etc, but not access_token
但是,POST只需要access_token,并且可以从Facebook中拉取名字,姓氏等所有信息。
However, the POST just needs the access_token and can pull all info like first name, last name, etc from Facebook.
如何在序列化程序中表达和编写get和post的这种不一致的性质
How can I express and code this assymetric nature of get and post in the serializer
.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
"""
User Serializer
"""
class Meta:
model = models.User
fields = ('id', 'username', 'first_name', 'last_name', 'image_url', 'activities', 'url', 'access_token')
.py
class UserViewSet(viewsets.ModelViewSet):
"""
List all users - this should be taken out as it would never be used in app, and we wont want this as well, as app can only view friend details
Gives details of an user - this should stay
"""
queryset = models.User.objects.all()
serializer_class = UserSerializer
任何这些选项:
- 使用
read_only
您不希望用户在创建时可以提供的字段。 - 覆盖
get_queryset
和为GET
vsPOST
返回不同的序列化程序。 - 编写
retrieve()
和create()
方法在ViewSet
- Use
read_only
on fields that you don't want the user to be able to supply on creation. - Either override
get_queryset
and return a different serializer forGET
vsPOST
. - Write the
retrieve()
andcreate()
methods on theViewSet
explicitily.
但是,POST只需要access_token,可以拉取所有信息,如名字,姓氏,等等。
However, the POST just needs the access_token and can pull all info like first name, last name, etc from Facebook.
你可能需要一个自定义的 restore_object
序列化器可以拉出该信息。
You'll probably need a custom restore_object
on the serializer to pull that info in.
这篇关于GET和POST在Django REST框架Serializer中的比较性质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!