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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With