我有一个带有外键的模型Book来模拟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吗?
答案 0 :(得分:0)
使用django中的反向查找
books = publisher.book_set.all()
但您仍需要对发布商进行迭代。