【问题标题】:DRF: How to access "context" inside custom DecimalField class?DRF:如何访问自定义 DecimalField 类中的“上下文”?
【发布时间】:2021-07-19 04:36:54
【问题描述】:

我从 Django RestFramework 继承 DecimalField 类,需要访问 context。十进制字段的格式包括用户可选择的设置,因此我需要访问 to_representation() 方法内的用户对象(我假设它应该在 context 内)。

通过调试,我查看了 CustomDecimalField 类中 self 的所有属性,但是,当然,我看不到类方法,所以我不知道是否有合适的“get”方法获取上下文。我试过self.context(作为属性)、self.get_context()self.getcontext(),但都没有成功。

我发现此公告回复:require_contexthttps://www.django-rest-framework.org/community/3.11-announcement/ ...但它似乎只对验证和默认值方法有效。

这似乎是一件很简单的事情;很难相信它是如此困难。

【问题讨论】:

    标签: django serialization django-rest-framework field


    【解决方案1】:

    您必须在上下文中手动设置用户。所以,在你看来:

    serializer = YourSerializer(your_data, context={'user': request.user})
    

    然后你就可以在你的 to_representation() 方法中访问它了:

    def to_representation(self, instance):
        user = self.context.get("user")
    

    请查看the documentation了解更多信息。

    【讨论】:

    • 谢谢@Mickael。大约在您发布答案的同时,我意识到我正在以错误的方法寻找它。我在__init__() 方法中查看self,而不是实际上在to_reqpresentation() 中。
    猜你喜欢
    • 1970-01-01
    • 2021-10-15
    • 2017-10-14
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 2012-05-15
    • 2018-01-13
    • 1970-01-01
    相关资源
    最近更新 更多