当前位置 : 主页 > 编程语言 > python >

drf字段自动填充当前用户信息

来源:互联网 收集:自由互联 发布时间:2022-10-26
只填充如果您希望它是“只写的”,需要用serializers.HiddenField,这意味着DRF会在写入时自动填充字段,而 不会在读取时返回User class ProjectSerializer(serializers.ModelSerializer): owner = serializers

drf字段自动填充当前用户信息_预处理

只填充如果您希望它是“只写的”,需要用serializers.HiddenField,这意味着DRF会在写入时自动填充字段,而不会在读取时返回User

class ProjectSerializer(serializers.ModelSerializer):
owner = serializers.HiddenField(default=serializers.CurrentUserDefault())

class Meta:
model = Project
fields = ['id', 'name', 'code', 'owner']
depth = 1


希望可读可写就需要用serializers.PrimaryKeyRelatedField

class ProjectSerializer(serializers.ModelSerializer):
owner = serializers.PrimaryKeyRelatedField(read_only=True)

class Meta:
model = Project
fields = ['id', 'name', 'code', 'owner']
depth = 1

class ProjectViewSet(viewsets.ModelViewSet):
serializer_class = ProjectSerializer
permission_classes = [permissions.IsAuthenticated]

def get_queryset(self):
user = self.request.user
return user.project_set.all()

# 预处理user相关
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
上一篇:Python教程Day01——Python概述
下一篇:没有了
网友评论