Django将JSON分配给模型对象

发布于 2025-02-07 06:24:33 字数 876 浏览 0 评论 0原文

我有此功能:

# create a function to upload an object one to one given a json
def upload_object_values(model, json_values):
if json_values:
    # the json values contain key value that match to the model
    # use a copy to avoid runtime error dictionary changing size
    for json_value in json_values.copy():
        # remove all ids in model copy
        if json_value[-3:] == '_id' or json_value == 'id':
            json_values.pop(json_value)

    # copy the object values only
    # TODO: ASSIGN json_values to the model object
    # save
    # model.save()

示例JSON_VALUES:

{'id': 1, 'notes': 'hello', 'name': 'world', 'phone': None, 'foreign_id': 2}

sample CleanEdjson_Values(删除ID和外键):

{'notes': 'hello', 'name': 'world', 'phone': None}

如何将这些值分配给我拥有的模型,每个密钥是我模型中具有相同名称的字段?

I have this function:

# create a function to upload an object one to one given a json
def upload_object_values(model, json_values):
if json_values:
    # the json values contain key value that match to the model
    # use a copy to avoid runtime error dictionary changing size
    for json_value in json_values.copy():
        # remove all ids in model copy
        if json_value[-3:] == '_id' or json_value == 'id':
            json_values.pop(json_value)

    # copy the object values only
    # TODO: ASSIGN json_values to the model object
    # save
    # model.save()

sample json_values:

{'id': 1, 'notes': 'hello', 'name': 'world', 'phone': None, 'foreign_id': 2}

sample cleanedjson_values (removed id and foreign keys):

{'notes': 'hello', 'name': 'world', 'phone': None}

How do I assign these values to the model that I have with each key being a field with the same name in my model?

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

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

发布评论

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

评论(1

俏︾媚 2025-02-14 06:24:33

这应该有效:

for key, value in json_values.items():
    setattr(model, key, value)
model.save()

This should work:

for key, value in json_values.items():
    setattr(model, key, value)
model.save()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文