Search code examples
djangomany-to-many

Django Many to One / One to Many relationships


I have two models, Book, and Author. Each Author has many books, and each book has many authors, so I set up a ManyToMany relation between Author and Book as the following:

class Author(models.Model):
    books = models.ManyToManyField(Book, related_name='authors')

class Book(models.Model):
    # some fields

I have certain alert IDs handy and I need to associate each book object with related authors, so I do (assume I have the id for all these objects handy):

author = Author.objects.get(pk=id)
book = Book.objects.get(pk=book_id)
author.books.add(book)
logger.debug(author.book_set.all())

I get the error:

AttributeError: 'Book' object has no attribute 'author_set'.

I am following convention from the django documentation here but it's not seeming to work for me: https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_many/

Can someone explain why I might be encountering this error?


Solution

  • Since the field is

    class Author:
        books = models.ManyToManyField(Book, related_name='authors')
    

    You should do

    logger.debug(author.books.all())
    

    The field names with _set appended are the defaults for following the relationship the other way, e.g. book.author_set.all(). However, you have set a related name, so you would use book.authors.all() instead,