我想让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.user
。serializers.CurrentUserDefault().email
出现错误'CurrentUserDefault' object has no attribute 'email'
如何将电子邮件默认设置为用户的电子邮件?在
这是
CurrentUserDefault
的文档所说的:您可以这样做,也可以在您的
views
中提供在context data
中传递的电子邮件id。重写函数get_serializer_context
在你的
^{pr2}$views
中。您的view
应该在某种继承级别上从GenericAPIView
扩展。现在在你的serializer
中,覆盖你的__init__
并获取你的电子邮件数据。在现在可以在序列化程序中使用它。在
请检查this answer中的解决方案2
代码可以是:
希望有帮助:)
相关问题 更多 >
编程相关推荐