只填充如果您希望它是“只写的”,需要用serializers.HiddenField,这意味着DRF会在写入时自动填充字段,而 不会在读取时返回User class ProjectSerializer(serializers.ModelSerializer): owner = serializers
只填充如果您希望它是“只写的”,需要用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)