我有这个功能:

# create a function to upload an object one to one given a json
def upload_object_values(model, json_values, update_if_exists=True):
    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)

        # assign a value to each key which is a the field in the given model
        for key, value in json_values.items():
            setattr(model, key, value)
        
        # if the object is get or create, or an update if exists
        if update_if_exists:
            # if it exists
            if model.__class__.objects.seal().exists():
                # retrieve the existing object
                retrieved_object = model.__class__.objects.seal().filter(json_values).first() #TODO: filter the model with the json_values
                # assign values into it
                retrieved_object = model
                # save
                retrieved_object.save()
                print(retrieved_object)
                print('existing, saved successfully')
            # if it does not exist
            else:
                # save
                model.save()
                print('does not exist, saved successfully')
        # else just save
        else:
            model.save()
            print('created successfully')

json\u值示例如下:

{'notes': '', 'name': 'test issuer', 'phone': None}

我需要能够使用我拥有的json\u值进行过滤,如下所示:

retrieved_object = model.__class__.objects.seal().filter(json_values).first() #TODO: filter the model with the json_values

如何才能在django中的filter()中指定这些值?

推荐答案

我想我理解你想要实现的目标.try 以下操作:

retrieved_object = model.__class__.objects.seal().filter(**json_values).first()

如果为json_values = {'notes': '', 'name': 'test issuer', 'phone': None},则上述行相当于:

retrieved_object = model.__class__.objects.seal().filter(notes='', name='test issuer', phone=None).first()

Json相关问答推荐

从Json响应中为需要每个值的Post请求提取多个值

如何将加权边列表导出到JSON树?

用于参考的Jolt变换

使用JQ将JSON输出转换为CSV复杂 struct

将 json 转换为 jsonb 安全吗?

当值包含ansible中的字符串时解析json值

PowerShell - 如何迭代 PSCustomObject 嵌套对象?

如何删除 django jsonfield 中的特定项目

序列化为json时如何忽略空列表?

如何从 rails 中的 respond_to 方法生成 json?

避免 KeyError 的默认字典键

JSON RPC - 什么是id?

苗条的 JSON 输出

Jackson 动态属性名称

我们可以使用 JSON 作为数据库吗?

是否可以将数据写入本地 json 文件,除了Angular 之外什么都没有?

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

如何在 Rails 模型中验证字符串是否为 json

我可以使用空字符串作为对象标识符吗?

MVC ajax json 发布到控制器操作方法