推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Raul7
V2EX  ›  Python

请教一个 Python 问题(应该是个比较简单的问题)

  •  
  •   Raul7 · Oct 14, 2022 · 2552 views
    This topic created in 1308 days ago, the information mentioned may be changed or developed.

    假如我有个数据查询方法,用户根据不同条件在库里根据不同的字段查询数据:

    def test(name){
        if name = 'a':
    	SqlModele.objects.filter(condition1='xxx').first()
        elif name = 'b':
         	SqlModele.objects.filter(condition2='xxx').first()
        elif name = 'c':
         	SqlModele.objects.filter(condition3='xxx').first()
    }
    

    请问我如何把上文代码中的查询条件( condition1 、condition2 、condition3 )通过函数传参的形式传入方法呢?想要的效果是:

    def test(name){
    
        if name = 'a':
    	query_condition=condition1
        elif name = 'b':
        	query_condition=condition2
        elif name = 'c':
        	query_condition=condition3
            
        SqlModele.objects.filter(query_condition='xxx').first()
    }
    
    7 replies    2022-10-19 05:38:29 +08:00
    erikk0
        1
    erikk0  
       Oct 14, 2022
    原生 sql 语句 fix everything
    mokiki
        2
    mokiki  
       Oct 14, 2022
    关键词 kwargs

    举例:

    d = {"k": 1}


    def f(k):
    print(k)


    f(**d)
    zhoudaiyu
        3
    zhoudaiyu  
    PRO
       Oct 14, 2022
    tristankuo
        5
    tristankuo  
       Oct 15, 2022
    SqlModele.objects.filter(**{query_condition:'xxx'}).first()
    amlee
        6
    amlee  
       Oct 19, 2022
    condition = {'a': condition1, 'b': condition2, 'c': codition3}

    def test(name){

    query_condition=condition[name]

    SqlModele.objects.filter(query_condition=query_condition).first()
    }
    amlee
        7
    amlee  
       Oct 19, 2022
    不是,我回完了才看出来,你这 python 的函数定义怎么有大括号啊。。。。。。。。。。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   989 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 22:05 · PVG 06:05 · LAX 15:05 · JFK 18:05
    ♥ Do have faith in what you're doing.