python - 具有 unique_together 约束的 django rest 序列化程序中的 read_only 字段

标签 python django serialization django-rest-framework

我想让电子邮件字段在默认的 django 用户模型中是唯一的。所以我做了 unique_together=[('email',)] 。现在在序列化程序中,我希望它是一个只读字段。 但是 Django Rest Framework 3.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:

user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())

serializers.CurrentUserDefault() 表示当前用户。我想将默认设置为用户的电子邮件。 serializers.CurrentUserDefault() 是否等同于 request.userserializers.CurrentUserDefault().email 给出错误 'CurrentUserDefault' object has no attribute 'email' 如何将电子邮件默认设置为用户的电子邮件?

最佳答案

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.

您可以这样做,也可以在 viewscontext data 中提供电子邮件 ID。覆盖函数 get_serializer_context

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

    return context

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

def __init__(self, instance = None,  data = serializers.empty, *args, **kwargs):
    self.email = kwargs['context']['email']

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

关于python - 具有 unique_together 约束的 django rest 序列化程序中的 read_only 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31912886/

相关文章:

python - 从父类别 django rest 获取所有产品

mysql - 如何编写迁移以使用 ManyToManyField 更改模型的主键

c# - 使用 JsConfig.ExcludeTypeInfo 时 ServiceStack session 不起作用

python - 量化随机性

python - 取决于行号的函数

python - Django 无法正确渲染 html 标签

serialization - Ansible:无法为顺序执行设置变量

c++ - 使用 boost 将二进制文件读入 std::vector?

使用属性装饰器的 Python 只读列表

python - Pandas DataFrame(长)至系列 ("wide")