V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2022-10-14 19:48:43 +08:00 · 1914 次点击
    这是一个创建于 550 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    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 条回复    2022-10-19 05:38:29 +08:00
    erikk0
        1
    erikk0  
       2022-10-14 19:57:38 +08:00
    原生 sql 语句 fix everything
    mokiki
        2
    mokiki  
       2022-10-14 20:03:12 +08:00
    关键词 kwargs

    举例:

    d = {"k": 1}


    def f(k):
    print(k)


    f(**d)
    zhoudaiyu
        3
    zhoudaiyu  
       2022-10-14 20:06:56 +08:00
    tristankuo
        5
    tristankuo  
       2022-10-15 19:14:52 +08:00
    SqlModele.objects.filter(**{query_condition:'xxx'}).first()
    amlee
        6
    amlee  
       2022-10-19 05:37:05 +08:00
    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  
       2022-10-19 05:38:29 +08:00
    不是,我回完了才看出来,你这 python 的函数定义怎么有大括号啊。。。。。。。。。。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2971 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:59 · PVG 22:59 · LAX 07:59 · JFK 10:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.