Question

I have the following models:

class Author(models.Model):
  author_name = models.CharField()

class Book(models.Model):
  book_name = models.CharField()

class AuthorBook(models.Model):
  author_id = models.ForeignKeyField(Author)
  book_id = models.ForeignKeyField(Book)

With that being said, I'm trying to emulate this query using the Django ORM (select all of the books written by a specific author, noting that Authors can have many books and Books can have many Authors):

SELECT book_name 
FROM authorbook, book
WHERE authorbook.author_id = 1
AND authorbook.book_id = book.id

I've read this FAQ page on the Django website, but before I modify my model structure and remove AuthorBook, I was curious if I could emulate that query using the current structure.

Was it helpful?

Solution

You should be able to do:

books = Book.objects.filter(authorbook__author_id=1)

to get a QuerySet of Book objects matching your author_id restriction.

The nice thing about Django is you can cook this up and play around with it in the shell. You may also find http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships to be useful.

OTHER TIPS

"AuthorBook" seems not correctly modeled.

You should use a ManyToManyField:

class Book(models.Model):
  name = models.CharField()
  authors = models.ManyToManyField(Author)

Then you can do:

books = Book.objects.filter(authors__id=1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top