gpt4 book ai didi

Django DRF 将 request.user 添加到模型序列化器

转载 作者:行者123 更新时间:2023-12-01 11:14:03 26 4
gpt4 key购买 nike

我正在使用 django rest 框架,并且我有一个通过模型 View 集和模型序列化器创建的对象。此 View 只能由经过身份验证的用户访问,并且对象应将其“uploaded_by”字段设置为该用户。

我已经阅读了文档,并得出结论,这应该可行

View 集:

class FooViewset(viewsets.ModelViewSet):
permission_classes = [permissions.IsAdminUser]
queryset = Foo.objects.all()
serializer_class = FooSerializer

def get_serializer_context(self):
return {"request": self.request}

序列化器:
class FooSerializer(serializers.ModelSerializer):
uploaded_by = serializers.PrimaryKeyRelatedField(
read_only=True, default=serializers.CurrentUserDefault()
)

class Meta:
model = Foo
fields = "__all__"

但是,这会导致以下错误:
django.db.utils.IntegrityError: NOT NULL constraint failed: bar_foo.uploaded_by_id

这表明“uploaded_by”没有被序列化程序填充。

根据我对文档的理解,这应该已将该字段添加到来自序列化程序的验证数据中,作为 create 方法的一部分。

显然我误解了一些东西!

最佳答案

问题出在read_only您的 uploaded_by 上的属性 field :

Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.

Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.



Source

基本上它用于显示对象的表示,但不包括在任何更新和创建过程中。

相反,您可以覆盖 create通过手动分配来存储所需用户的功能。
class FooSerializer(serializers.ModelSerializer):

uploaded_by = serializers.PrimaryKeyRelatedField(read_only=True)

def create(self, validated_data):
foo = Foo.objects.create(uploaded_by=self.context['request'].user,
**validated_data)
return foo

关于Django DRF 将 request.user 添加到模型序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55549912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com