将序列化对象添加到当前用户

时间:2015-04-03 20:25:20

标签: django django-rest-framework

所以我有一个视图接受序列化的Album对象并将所有者分配给当前用户

class AlbumListViewer(APIView):    
    def post(self, request, format = None):
        request.data['user_id'] = request.user.id
        serializer = AlbumSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(status.HTTP_201_CREATED)
        return Response(status = status.HTTP_400_BAD_REQUEST)

我得到的错误是

  列“user_id”中的

空值违反了非空约束

My Serializer看起来像这样

class AlbumSerializer(serializers.ModelSerializer):

    user = serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
        model = Album
        fields = ('id','album_name', 'date_created','user')

最后我的模型看起来像这样

class Album(models.Model):
    user = models.ForeignKey(User)
    album_name = models.CharField(max_length=30)
    date_created = models.DateTimeField(editable=False, auto_now_add=True)

我尝试在JSON数据中分配一个用户ID,但序列化程序无法识别它,无论如何分配这个序列化对象并在保存前给它一个拥有者?

1 个答案:

答案 0 :(得分:0)

您的AlbumListViewer中存在一些问题。不要尝试添加validatated_data任何东西。而是将partial = True传递给序列化程序,并在验证后使用save()方法保存缺失值。

class AlbumListViewer(APIView):   
    def post(self, request, format = None):
        serializer = AlbumSerializer(data=request.data, partial=True)
        if serializer.is_valid():
            user = request.user
            serializer.save(user=user)
            return Response(status=status.HTTP_201_CREATED)
        return Response(status = status.HTTP_400_BAD_REQUEST)