推荐学习书目
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 · Sep 9, 2015 · 3507 views
    This topic created in 3902 days ago, the information mentioned may be changed or developed.

    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 replies    2015-09-10 14:00:29 +08:00
    IanPeverell
        1
    IanPeverell  
       Sep 9, 2015
    $python manage.py shell

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

    不知道你是不是问的是这个…
    wenbinwu
        2
    wenbinwu  
       Sep 9, 2015   ❤️ 1
    > books = B.objects.select_related ('author').all ()
    > [(b.author.name, b.name ) for b in books]
    这样?
    erevus
        3
    erevus  
    OP
       Sep 10, 2015
    @wenbinwu books = B.objects.select_related ('author').all () 对 就是这个
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2849 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 1212ms · UTC 11:39 · PVG 19:39 · LAX 04:39 · JFK 07:39
    ♥ Do have faith in what you're doing.