简体   繁体   English

使用django rest框架时,如何强制将用户ID作为值?

[英]How can I force the user id as value when working with django rest framework?

I want my rest api to be able to add objects, but there is a twist. 我希望我的rest api能够添加对象,但是有一个转折。

My model has a field that's called user which can either be None for anonymous users or the id of whoever sets it. 我的模型有一个称为user的字段,对于匿名用户可以为None,也可以为设置该字段的人的ID。

How can I enforce this in an elegant way? 我如何以一种优雅的方式执行此操作?

Also if the user field is None I want the id of the new object to be stored in an array in the anonymous users session so it can be assigned if he ever decides to register. 另外,如果user字段为None,我希望将新对象的ID存储在匿名用户会话中的数组中,以便在他决定注册时可以对其进行分配。

Here is how I created the viewset: 这是我创建视图集的方式:

class PointAPIView(viewsets.ModelViewSet):
    queryset = Point.objects.all()
    serializer_class = PointSerializer
    permission_classes = (IsOwnerOrReadOnly,)

I suspect that I have to write a custom create method is that right? 我怀疑我必须编写一个自定义的create方法,对吗? If so how does it need to look like? 如果是这样,它的外观如何? The documentation only says that it's there, but not how it needs to be structured and what it needs to return. 该文档仅说它在那里,但没有说明它的结构方式以及返回的内容。 Can you show me an example of a dummy method where I can put my logic? 能否给我展示一个虚拟方法的示例,我可以在其中放置我的逻辑?

Thank you for your time! 感谢您的时间!

EDIT: Because someone asked. 编辑:因为有人问。 The Model would look something like this: 该模型将如下所示:

class Point(models.Model):
  user = models.ForeignKey('auth.User')
  value = models.IntegerField()

Now the question is how I can force the user field to be request.user when creating a point object via the rest api. 现在的问题是,当通过rest api创建点对象时,如何强制user字段为request.user。

In your PointSerializer override create method and get request object to extract current user and assign it to created point. PointSerializer重写create方法并获取请求对象以提取当前用户并将其分配给创建的点。

class PointSerializer(serializers.ModelSerializer):
     //point fields

    class Meta:
          model = Point
          fields = ('value','user')

    def create(self,validated_data):
        request = request = self.context['request']
        user = request.user
        point = Point.objects.create(value=validated_data['value'])
        point.user = user
        point.save()
        return point

not sure if you can nodify validated_data , if not you'd need to copy it over 不知道是否可以提名validated_data ,如果不能,则需要将其复制

def create(self, validated_data):
    request = self.context['request']
    user = request.user

    if user.is_authenticated():
        validated_data.update({
            'user': user.id
        })

    point = Point.objects.create(**validated_data)

    return point

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM