用json值过滤Django模型



我有这个函数:

# 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_values:

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

我需要能够使用我所拥有的json_values进行过滤,如以下行所示:

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

我怎样才能在django的filter()中分配这些值?

我想我明白你想达到的目的。试试这个:

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()

要在Django中使用JSONField来过滤,你应该使用__(double)。

YourObject.objects.filter(json_values__notes='')
YourObject.objects.filter(json_values__name='test issuer')

如果你想有更深的字典层次,规则保持不变:

{'notes': {'casual': 'nice', 'pro': 'elegant'}, 'name': 'test issuer', 'phone': None}
YourObject.objects.filter(json_values__notes__pro='elegant')

相关内容

  • 没有找到相关文章

最新更新