【发布时间】:2015-11-12 15:25:06
【问题描述】:
如果我这样做了
books = Book.objects.filter(author__name="John")
我只得到Book 的字段
我怎样才能获得Author 的字段,通过单个查询?
【问题讨论】:
-
你可以使用
annotate
标签: python sql django django-queryset django-orm
如果我这样做了
books = Book.objects.filter(author__name="John")
我只得到Book 的字段
我怎样才能获得Author 的字段,通过单个查询?
【问题讨论】:
annotate
标签: python sql django django-queryset django-orm
Books.objects.select_related('author').filter(author__name="John")
你只需要这样做。
这将在一个查询中获取相关对象。
【讨论】:
使用values 或values_list:
books_info = Book.objects.filter(author__name="John").values('book_field1', 'book_field2', 'book__author_field1','book__author_field2')
django 文档:
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#values https://docs.djangoproject.com/en/1.8/ref/models/querysets/#values-list
【讨论】:
select_related 的性能要好得多,我会坚持下去。