开发者

django make query

DB TABLE

select * from AAA;
id   |    Name     |    Class  | Grade    |
--------------------------------------
1    |     john    |      1    |   A      |
2    |     Jane    |      2    |   B      |
3    |     Joon    |      2    |   A      |
4    |     Josh    |      3    |   C      |

|

Code

Django
search_result = AAA.objects.filter(Grade = 'B').count() 
print search_r开发者_JAVA技巧esult 

search_result -> 2

I want to change Grade to Class by VALUE.

Django
target_filter = 'Class'
search_result = AAA.objects.filter(__"target_filter..."__ = '3').count()

search_result -> 1

Q) How can I complete this code? Is it possible?


Maybe you can do it like this:

target_filter = 'Class'
filter_args = {target_filter: 3}
search_result = AAA.objects.filter(**filter_args).count()


you can shorten aeby's example by putting the kwargs in directly

target_filter = 'Class'
search_result = AAA.objects.filter(**{target_filter:3}).count()


It is somehow the same answer I gave here. You can also use the getattr but now with the module object itself. This is either __module__ if it is the same module, or the module you imported.

target_filter = 'Class'
search_result = AAA.objects.filter(getattr(__module__, target_filter) = '3').count()

EDIT: I got it wrong, it is not possible to access the current module via __module__. If the class is declared in the same module as your search, you can use globals()[target_filter] to access it. If your search is from another module, you can do it like this:

import somemodule

...

target_filter = 'Class'
search_result = AAA.objects.filter(getattr(somemodule, target_filter) = '3').count()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜