Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

django - Dynamic variable name in python

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.

field_name = funct()
locations = Locations.objects.filter(field_name__lte=arg1)

where if funct() returns name would equal to

locations = Locations.objects.filter(name__lte=arg1)

Not sure how to do that ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...