django 的 ForeignKey 查询问题

2015 年 9 月 9 日
 erevus

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"
这样的数据?

3686 次点击
所在节点    Python
3 条回复
IanPeverell
2015 年 9 月 9 日
$python manage.py shell

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

不知道你是不是问的是这个…
wenbinwu
2015 年 9 月 9 日
> books = B.objects.select_related ('author').all ()
> [(b.author.name, b.name ) for b in books]
这样?
erevus
2015 年 9 月 10 日
@wenbinwu books = B.objects.select_related ('author').all () 对 就是这个

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://v2ex.ih06.com/t/219403

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX