Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the Django ORM to query this many-to-many example?

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.

like image 290
Huuuze Avatar asked Feb 10 '09 19:02

Huuuze


People also ask

How fetch data from many-to-many field in Django?

A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.

How do you do a many-to-many relationship in Django?

To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.

How does many-to-many field work in Django?

A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.


1 Answers

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.

like image 94
Emil Sit Avatar answered Sep 20 '22 03:09

Emil Sit