Django Rest Framework在序列化之前更新数据 [英] Django Rest Framework update data before serialize

查看:64
本文介绍了Django Rest Framework在序列化之前更新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望任何用户都可以使用我的RESTful API创建自己的产品.为此,我创建了一个继承ListCreateAPIView的视图.问题在于用户只能创建自己拥有的产品,因此在创建Product模型的实例时,我希望所有者"字段对应于已通过身份验证的用户.

I want that any user could create their own products with my RESTful API. For this purpose, I created a view that inherits ListCreateAPIView. The problem is that a user should only create products that he/she own, so when the instance of the Product model is created, I wanted that the field Owner corresponds to the user that is authenticated.

这是我的产品型号

class Product(models.Model):
    owner = models.ForeignKey(User)
    name = models.CharField(max_length=30)

很明显,我的序列化器是:

Obviously my serializer is:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Product

和我的观点:

class ProductView(generics.ListCreateAPIView):
    queryset = models.Product.objects.all()
    serializer_class = serializers.ProductSerializer
    permission_classes = (IsAuthenticatedOrReadOnly,)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        #serializer.initial_data['owners'] = models.Person.objects.get(user__email=request.user).user_id
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

如您所见,我尝试修改"initial_data",但这是一个QueryDict,它是不可变的.另一个选择是将其转换为Python字典,然后添加所有者"值,但是这样做时,我将每个值都作为列表获取(即{'name':['MyName']}),所以这将是一个非常解决这个问题的方法很丑,我认为这应该是一个更直接的解决方案.

As you can see, I tried modifying the "initial_data", but it is a QueryDict, which is inmutable. Another option is transforming it into a Python dict and then adding the "owner" value, but at doing that I get every value as a list (i.e. {'name': ['MyName']}), so it would be a very ugly way to solve the problem, I think it should be a more straightforward solution.

推荐答案

您可以覆盖 perform_create() 并将当前用户作为 owner 代码>.然后,当创建 Product 实例时,将使用当前用户值保存 owner 字段.

You can override perform_create() and pass the current user as the owner. Then, when the Product instance will be created, owner field will be saved with the current user value.

class ProductView(generics.ListCreateAPIView):
    queryset = models.Product.objects.all()
    serializer_class = serializers.ProductSerializer
    permission_classes = (IsAuthenticatedOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user) # pass the current user as the 'owner'

此外,您还应该在序列化程序中定义 owner 字段为

Also, you should define owner field in your serializer as read_only. Then the field will not be required during deserialization. But, this field will be included in the output on serialization.

 class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Product
        extra_kwargs = {'owner': {'read_only':True}} # set 'owner' as read-only field 

这篇关于Django Rest Framework在序列化之前更新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆