-1

I have a model Book with a foreign key to model Publisher.

class Publisher(models.Model):
   ...

class Book(models.Model):
    publisher = models.ForeignKey(Publisher)
    ...

Is it possible to get one publisher with its all books (or with some condition)? So the values of the queryset may like below:

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"
        },
    ]
}]

This seems a combination of two querysets in How to combine 2 or more querysets in a Django view, but they are not quite the same. And there is a way to combine them after get the list of the query:

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)

But is it possible to use a QuerySet without iterating the publishers?

Community
  • 1
  • 1
qiwihui
  • 63
  • 1
  • 4
  • 10

1 Answers1

0

Use the reverse lookup in django

books = publisher.book_set.all()

But you still need to iterate over the publishers.