Dynamic variable name in python

后端 未结 1 1033
野的像风
野的像风 2020-12-03 23:46

I\'d like to call a query with a field name filter that I wont know before run time... Not sure how to construct the variable name ...Or maybe I am tired.

fi         


        
相关标签:
1条回答
  • 2020-12-03 23:55

    You can create a dictionary, set the parameters and pass this to the function by unpacking the dictionary as keyword arguments:

    field_name = funct()
    params = {field_name + '__lte': arg1,       # field_name should still contain string
              'some_other_field_name': arg2}
    
    locations = Locations.objects.filter(**params)
    
    # is the same as (assuming field_name = 'some_name'):
    # Locations.objects.filter(some_name__lte=arg1, some_other_field_name=arg2)
    
    0 讨论(0)
提交回复
热议问题