如何在不使用字段名的情况下运行 django orm 查询?

Posted

技术标签:

【中文标题】如何在不使用字段名的情况下运行 django orm 查询?【英文标题】:How to run django orm query without using field name? 【发布时间】:2021-12-01 20:32:57 【问题描述】:

所以我有一个 json 数据,其中包含模型的字段名称作为带有值的 json 键。我想在运行时运行 orm 查询并定义字段名称。

例如:

json_data = "postgres_id":"10"

query = AcronymSecurityControlMaster.objects.get(postgres_id=10) 

json_data = "age":"10"

query = AcronymSecurityControlMaster.objects.get(age=10) 

【问题讨论】:

【参考方案1】:

您可以使用字典解包将字典作为函数调用的命名参数传递:

json_data = "age": 10
#                           dictionary unpacking ↓↓
query = AcronymSecurityControlMaster.objects.get(**json_data)

但是,您应该确认json_data 不包含任何安全漏洞。例如,用户可以尝试通过以下方式“猜测”敏感数据:

 userfield__name='aabbcc' 

您可能不想共享用户名。

【讨论】:

以上是关于如何在不使用字段名的情况下运行 django orm 查询?的主要内容,如果未能解决你的问题,请参考以下文章