Django rest序列化程序中的只读字段,具有唯一的\u together contrain

2024-04-19 23:25:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让email字段在默认django用户模型中是唯一的。所以我做了unique_together=[('email',)]。现在在序列化程序中,我希望它是一个只读字段。 但是Django Rest framework3.0文档说:

There is a special-case where a read-only field is part of a unique_together constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.

The right way to deal with this is to specify the field explicitly on the serializer, providing both the read_only=True and default=… keyword arguments.

One example of this is a read-only relation to the currently authenticated User which is unique_together with another identifier. In this case you would declare the user field like so:

用户=序列化程序.PrimaryKeyRelatedField(只读=真, 违约=序列化程序.CurrentUserDefault())

在序列化程序.CurrentUserDefault()表示当前用户。我想将默认值设置为用户的电子邮件。serializers.CurrentUserDefault()不等于request.userserializers.CurrentUserDefault().email出现错误'CurrentUserDefault' object has no attribute 'email'如何将电子邮件默认设置为用户的电子邮件?在


Tags: theto用户程序fieldonlyread序列化
2条回答

这是CurrentUserDefault的文档所说的:

A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.

您可以这样做,也可以在您的views中提供在context data中传递的电子邮件id。重写函数get_serializer_context

def get_serializer_context(self):
    context = super(YourClass, self).get_serializer_context()
    context['email'] = request.user.email

    return context

在你的views中。您的view应该在某种继承级别上从GenericAPIView扩展。现在在你的serializer中,覆盖你的__init__并获取你的电子邮件数据。在

^{pr2}$

现在可以在序列化程序中使用它。在

请检查this answer中的解决方案2

代码可以是:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email',)
        extra_kwargs = {
            'email': {'read_only': True},
        }


    def create(self, validated_data):
        """Override create to provide a email via request.user by default."""
        if 'email' not in validated_data:
            validated_data['email'] = self.context['request'].user.email

        return super(UserSerializer, self).create(validated_data)

希望有帮助:)

相关问题 更多 >