这与问题Assymetric nature of GET and POST in a Django REST framework Serializer有关。我把它作为一个新问题,而不是在该主题中提出更多问题,而不是SO指南
我正在为User模型编写一个Viewset和一个ModelSerializer来提供一个/ user端点
GET
- 以标准DRF方式返回所有用户的列表和信息
POST
- 我希望客户端发布的是facebook access_token(因此将所有其他字段作为read_only放在序列化程序中.ViewSet中的pre_save()连线使用此访问令牌并使用{{ 1}}从facebook api中提取数据(使用访问令牌)并自动创建一个包含该信息的新用户。由于这个新的 django-facebook
是自动创建的,我想抑制正常的DRF在POST期间流动而不是通过DRF创建另一个用户。我该怎么做?
views.py
user
serializers.py
from open_facebook import OpenFacebook
from django_facebook.api import FacebookUserConverter
from django_facebook.connect import connect_user
class UserViewSet(viewsets.ModelViewSet):
queryset = models.User.objects.all()
serializer_class = UserSerializer
def pre_save(self, obj):
access_token = obj.access_token
facebook = OpenFacebook(access_token)
conv = FacebookUserConverter(facebook)
action, user = connect_user(self.request, access_token)
# this creates an entire new row, just as required, in the variable "user", so all I want to do is suppress any other row creation in the standard POST method. connect_user fills in data like first_name, last_name, etc from facebook already, and that is exactly what I need to do.
conv.get_and_store_friends(user)
obj = user
user.delete()
# I am trying to do that by copying user to obj and deleting user, but at the end of it i
print obj.username
答案 0 :(得分:1)
使用ModelViewSet的create()函数工作,而不是pre_save - 来禁止保存对象