【问题标题】:How to run django orm query without using field name?如何在不使用字段名的情况下运行 django orm 查询?
【发布时间】: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) 

【问题讨论】:

    标签: python django django-models django-rest-framework django-orm


    【解决方案1】:

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

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

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

    { userfield__name='aabbcc' }
    

    您可能不想共享用户名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 2016-01-15
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      • 2021-01-17
      相关资源
      最近更新 更多