Django REST框架序列化程序中GET和POST的不对称性质 [英] Asymmetric 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.
我如何在序列化器中表达和编码获取和发布的这种不对称性质
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 $返回一个不同的序列化器。 c $ c>与
POST
。 - 编写
retrieve()
并明确地在ViewSet
上的create()
方法。
- 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即可从Facebook提取名字,姓氏等所有信息。
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.
这篇关于Django REST框架序列化程序中GET和POST的不对称性质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!