【发布时间】:2016-05-09 16:58:58
【问题描述】:
我有一本带有外键的模型书来模拟 Publisher。
class Publisher(models.Model):
...
class Book(models.Model):
publisher = models.ForeignKey(Publisher)
...
是否可以让一个出版商拥有所有书籍(或在某些条件下)?因此查询集的值可能如下所示:
publishers = Publisher.objects.filter(name__isstartwith='publisher')
publishers_dict = publishers.values()
[{
"id": 1,
"name": "publisher_a",
"books":[
{
"id": 1,
"name": "book_name_1"
},
{
"id": 2,
"name": "book_name_2"
},
]
}]
这似乎是How to combine 2 or more querysets in a Django view 中两个查询集的组合,但它们并不完全相同。 并且有一种方法可以在获取查询列表后将它们组合起来:
publishers = Publisher.objects.filter(name__isstartwith='publisher')
publishers = list(publishers)
# then filter the publishers to get all books from is
for pub in publishers:
books = Books.objects.filter(publish=pub["id"])
books = list(books)
setattr(pub, "books", books)
但是是否可以在不迭代发布者的情况下使用 QuerySet?
【问题讨论】:
-
您是在询问相关对象的序列化,还是只是关于如何一次性获取它们?因为
prefetch_related会做后者。 -
这似乎是我正在寻找的。非常感谢。
标签: python django django-queryset