我正在使用 Django 1.5 和 Django REST Framework 2
我已经重写了create
方法来添加验证并手动返回Response。
我的看法就像
class MultiUserCreateListView(generics.ListCreateAPIView):
model = MultiUser
serializer_class = MultiUserSerializer
def get_queryset(self):
users = MultiUser.objects.get_shared_users(user=self.request.user)
return users
def create(self, request, *args, **kwargs):
email = request.DATA.get('email', None)
access_level = request.DATA.get('access_level', None)
name = request.DATA.get('name', None)
user = User.objects.filter(email=email)
if user:
return Response({'message': 'Email address already in use.'}, status=status.HTTP_400_BAD_REQUEST)
serializer = self.get_serializer(data=request.DATA)
new_user = create_active_user(request, self, email, email, password=None, is_shared=True)
if new_user:
if serializer.is_valid():
multi_user_obj = MultiUser(
user=self.request.user,
shared_user=new_user,
access_level=access_level
)
multi_user_obj.save()
serializer2 = MultiUserSerializer(data=multi_user_obj)
return Response(serializer2.data, status=status.HTTP_201_CREATED)
else:
return Response({'message': 'Unable to create user. Try again'})
但是对于MultiUserSerializer
{"id": "", "shared_user_name": "", "shared_user_email": "", "access_level": "", "invitation_sent_on": null, "invitation_accepted_on": null, "is_invitation_sent": "", "is_invitation_accepted": "", "created": null, "updated": null}
在打印print(multi_user_obj.id)
时给出正确的ID。
为什么不序列化?
编辑2:序列化器
class MultiUserSerializer(serializers.ModelSerializer):
shared_user_email = serializers.Field(source='shared_user.email')
shared_user_name = serializers.Field(source='shared_user.first_name')
is_invitation_sent = serializers.Field(source='is_invitation_sent')
is_invitation_accepted = serializers.Field(source='is_invitation_accepted')
class Meta:
model = MultiUser
fields = (
'id', 'shared_user_name', 'shared_user_email',
'access_level', 'invitation_sent_on', 'invitation_accepted_on',
'is_invitation_sent', 'is_invitation_accepted',
'created', 'updated'
)
答案 0 :(得分:3)
您必须通过instance
而不是data
传递实例
serializer2 = MultiUserSerializer(instance=multi_user_obj)