在数据被请求替换之前访问查询

2024-09-29 17:09:56 发布

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

我在tastype中使用一个补丁请求来更新模型中的一个字段,但是当这个补丁通过时,我尝试附加数据库中已经存在的数据,而不是完全替换该值。你知道吗

Example: In a blog post, a user flags a post as inappropriate. You want to get this user's UserID and append it to a field, flaggedUserID. flaggedUserID will contain this user's ID along with anyone else who has flagged the post previously.

在tastype中,我很难找到一个钩子,通过这个钩子,我可以在将请求中的值复制到查询中的数据之前访问查询。我尝试了“alter\u deserialized\u detail\u data(self,request,data)”钩子,但是传递给这个函数的数据参数中的值已经被替换。你知道吗

有人有什么建议吗?你知道吗


Tags: to数据in模型数据库dataexampleblog
1条回答
网友
1楼 · 发布于 2024-09-29 17:09:56

在阅读了tastypie的源代码之后,我得出了以下解决方案:

从请求到查询的数据复制似乎发生在“update\ in\ place”函数中。通过以以下方式重写此函数,我能够实现我想要的结果:

def update_in_place(self, request, original_bundle, new_data):
    """
    Update the object in original_bundle in-place using new_data.
    """

    """Right here I am checking if the parameter flaggedUserID is in the 
    request (PATCH saves request data to request.body).  If this is false then 
    copy the new data into the query, otherwise jump to 
    alter_deserialized_detail_data where I am handling the appending of the data 
    from the request. """

    if 'flaggedUserID' not in request.body:
        original_bundle.data.update(**dict_strip_unicode_keys(new_data))

    # Now we've got a bundle with the new data sitting in it and we're
    # we're basically in the same spot as a PUT request. SO the rest of this
    # function is cribbed from put_detail.
    self.alter_deserialized_detail_data(request, original_bundle.data)
    kwargs = {
        self._meta.detail_uri_name: self.get_bundle_detail_data(original_bundle),
        'request': request,
    }
    return self.obj_update(bundle=original_bundle, **kwargs)

根据目标的不同,我可能会建议你多清理一点。我只想以最基本的形式展示这段代码,而不必发布多个函数并开始迷惑人们。你知道吗

相关问题 更多 >

    热门问题