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
erevus
V2EX  ›  Python

django 的 ForeignKey 查询问题

  •  1
     
  •   erevus · 2015-09-09 16:11:10 +08:00 · 2835 次点击
    这是一个创建于 3151 天前的主题,其中的信息可能已经有所发展或是发生改变。

    models.py

    class A (models.Model ):
        name = models.CharField (u'作者')
      class B (models.Model ):
        author = models.ForeignKey (A )
        book = models.CharField (u'书籍')
    

    怎么查询出所有
    "A.name,B.book"
    这样的数据?

    3 条回复    2015-09-10 14:00:29 +08:00
    IanPeverell
        1
    IanPeverell  
       2015-09-09 19:01:28 +08:00
    $python manage.py shell

    >>>from XXX.models import A,B
    >>>A.objects.all (),B.objects.all ()

    不知道你是不是问的是这个…
    wenbinwu
        2
    wenbinwu  
       2015-09-09 19:09:16 +08:00   ❤️ 1
    > books = B.objects.select_related ('author').all ()
    > [(b.author.name, b.name ) for b in books]
    这样?
    erevus
        3
    erevus  
    OP
       2015-09-10 14:00:29 +08:00
    @wenbinwu books = B.objects.select_related ('author').all () 对 就是这个
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2840 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 15:30 · PVG 23:30 · LAX 08:30 · JFK 11:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.