推荐学习书目
› 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
daimoon
V2EX  ›  Python

请教一个 django 数据库查询字段重命名的问题

  •  
  •   daimoon · May 18, 2016 · 5351 views
    This topic created in 3784 days ago, the information mentioned may be changed or developed.
    比如下面这段:
    m.User.objects.values('id', 'coreuserwxprofile__nickname').filter(
    coreuserwxprofile__nickname__contains=q).all()[0:20]
    我要是希望返回结果是这样的:
    [{'id':1,'nick':'tom'}]
    应该怎么做呢?
    谢谢~~~
    4 replies  •  2016-05-27 16:13:12 +08:00
    linuxchild
        1
    linuxchild  
       May 18, 2016
    In [9]: a = [{'name': 'wang', 'id': 1}, {'name': 'zhao', 'id': 2}]

    In [10]: [{'nick': i['name'], 'id': i['id']} for i in a]
    Out[10]: [{'id': 1, 'nick': 'wang'}, {'id': 2, 'nick': 'zhao'}]
    yutian2211
        2
    yutian2211  
       May 18, 2016   ❤️ 1
    from django.db.models import F

    User.objects.annotate(nickname=F('coreuserwxprofile__nickname')).values('id','nickname').filter(
    coreuserwxprofile__nickname__contains=q).all()[0:20]



    -------------------
    网上可以搜得到的
    daimoon
        3
    daimoon  
    OP
       May 19, 2016
    @yutian2211 谢谢啊。 annotate 真是用不熟。 extra 也可以的。.extra(select={'nick': 'coreuserwxprofile.nickname'}
    daimoon
        4
    daimoon  
    OP
       May 27, 2016
    谢谢大家啊。最后我就是用的 yutian 的 annotate :)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2831 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 13:13 · PVG 21:13 · LAX 06:13 · JFK 09:13
    ♥ Do have faith in what you're doing.