发布于 2025-01-28 08:08:34 字数 452 浏览 1 评论 0 原文

我已经看到了很多次,到处都是它,但无法弄清楚它的实际含义,这是必不可少的吗?我以前没有在代码中使用此 data._mutable = true或false ,我不确定是否应该使用它。

代码片段看起来有点像这样。

def update(self, request, *args, **kwargs):
        instance = self.get_object()
        data = request.data
        if data.get("something") == "null":
            data._mutable = True
            data["something"] = None
            data._mutable = False

为什么我们需要为数据对象的私有属性分配true或false。

I have seen this many times and looked it everywhere but couldn't figure out what it actually means and is it mandatory? I have not used this data._mutable = True or False in my code before and I am not sure whether I should be using it or not.

The code snippet looks somewhat like this.

def update(self, request, *args, **kwargs):
        instance = self.get_object()
        data = request.data
        if data.get("something") == "null":
            data._mutable = True
            data["something"] = None
            data._mutable = False

Why do we need to assign True or False to the private attribute _mutable of data object.??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦忆晨望 2025-02-04 08:08:34

如果您用作解析器a 代码>   [drf-doc] partparser   [drf-doc] ,或另一个解析的解析器a >   [django-doc] ,那么 queryDict 默认情况下是不可分割的。 That means that it will reject any changes to it, so you can not add, remove or edit key-value pairs.

By setting the ._mutable attribute, you can prevent this from raising errors, and thus mutate the QueryDict.但这不是很好的做法,因为没有记录您可以通过将 querydict 通过设置 ._ mutable 属性为 true 来使其变为可变。通常,您可以使用

def update(self, request, *args, **kwargs):
        instance = self.get_object()
        data = request.data
        if data.get('something') == 'null':
            data = data.copy()
            data['something'] = None
        # …

If you use as parser a FormParser [drf-doc] or MultiPartParser [drf-doc], or another parser that parses to a QueryDict [Django-doc], then the QueryDict is by default immutable. That means that it will reject any changes to it, so you can not add, remove or edit key-value pairs.

By setting the ._mutable attribute, you can prevent this from raising errors, and thus mutate the QueryDict. But it is not good practice, since it is not documented that you can make the QueryDict mutable by setting the ._mutable attribute to True. Usually you work with .copy() [Django-doc] which will return a mutable deep copy, so:

def update(self, request, *args, **kwargs):
        instance = self.get_object()
        data = request.data
        if data.get('something') == 'null':
            data = data.copy()
            data['something'] = None
        # …
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文