Search code examples
djangodjango-modelsdjango-related-manager

List of publishers for an author


This works, but is there a Django idiom that does it better?

my_books = Book.objects.filter(author__name=='me')
my_publishers = Publisher.objects.filter(pk__in=[b.publisher.id for b in my_books])

models = round_up_the_usual_suspects()

class Publisher(models.Model):
    name = models.CharField(max_length=30)


class Author(models.Model):
    name = models.CharField(max_length=30)


class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, related_name='books_authored')
    publisher = models.ForeignKey(Publisher, related_name='books_published')

Solution

  • You can do

    my_publishers = Publisher.objects.filter(book__author__name='me')
    

    This gives you all the publishers for the book authored by me