Mad's Man
Mad's Man

Reputation: 123

How to run django orm query without using field name?

So i have one json data that contain field name of model as json key with value. i want to run orm query and define field name on run time.

Ex:

json_data = {"postgres_id":"10"}

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

json_data = {"age":"10"}

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

Upvotes: 1

Views: 107

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You can use dictionary unpacking to pass a dictionary as the named parameters of a function call:

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

You however should validate that the json_data does not contain any security vulnerabilities. For example a user could try to "guess" sensitive data with:

{ userfield__name='aabbcc' }

where you perhaps do not want to share the name of the user.

Upvotes: 1

Related Questions