gpt4 book ai didi

django-rest-framework - Django Rest 框架 : make a serializer field not required in post data when perform create re

转载 作者:行者123 更新时间:2023-12-04 01:43:36 25 4
gpt4 key购买 nike

我有以下设置:

模型.py

class QuoteModel(models.Model):
"""
this model stores initial information for the Quote
"""
quote_number = models.CharField(max_length=20,
unique=True,
help_text="Please use the quote number from pms",)
description = models.CharField(max_length=200,
help_text="Enter description that you might find helpful")
creator = models.ForeignKey(User)
date_created = models.DateField(auto_now_add=True)

Serializer.py
# Serializers define the API representation.
class QuoteModelSerializer(serializers.ModelSerializer):
class Meta:
model = Quote
fields = ('id', 'quote_number', 'description', 'creator', 'date_created')
read_only_fields = ('date_created',)

查看.py
class QuoteListCreateView(generics.ListCreateAPIView):
queryset = Quote.objects.all()
serializer_class = QuoteModelSerializer
permission_classes = (permissions.IsAuthenticated, )

def perform_create(self, serializer):
serializer.save(creator=self.request.user)

在代码片段中,我正在设置 creator领域 QuoteModel在 View 的 perform_create方法。自 QuoteListCreateView是仅经过身份验证的 View ,因此,我不想通过 creator在报价创建请求期间(发布到 /quotes )。 creator是序列化程序类的一部分,如果我没有通过创建者,发布请求将返回以下内容。
“创造者”:[
“此字段是必需的。”
]”

因此,我的问题是——
有没有办法制作 creator发布请求中的参数可选?我无法添加 null=truecreator model.py 中的字段,因为从模型的角度来看它是必需的。

提前致谢。

修复

覆盖 creator模型序列化程序中的属性并将 required 设置为 False 解决了该问题。
class QuoteModelSerializer(serializers.ModelSerializer):
creator = serializers.PrimaryKeyRelatedField(required=False, queryset=User.objects.all())
class Meta:
model = Quote
fields = ('id', 'quote_number', 'description', 'creator', 'date_created')
read_only_fields = ('date_created',)

最佳答案

根据您对问题的描述。具体来说:

I don't want to pass the creator during the quote create request.



听起来您希望创建者字段是只读的,但在创建时填充。如果是这种情况,我建议您使用以下方法:
class QuoteModelSerializer(serializers.ModelSerializer):
creator = serializers.PrimaryKeyRelatedField(
read_only=True,
default=serializers.CurrentUserDefault()
)
class Meta:
model = Quote
fields = ('id', 'quote_number', 'description', 'creator', 'date_created')
read_only_fields = ('date_created',)

关于django-rest-framework - Django Rest 框架 : make a serializer field not required in post data when perform create re,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45289025/

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