Durand
Durand

Reputation: 897

Django: Referencing a manytomany field that has been defined in another model

I'm trying to work out how to calculate the number of books written by an author. The book model sets up the manytomany field with the author model. I have no idea how even google something like this which I thought would be very simple to do but I don't even know how to start.

Here's the stripped down code:

class Author(models.Model):
    first_name = models.CharField()
    last_name = models.CharField()

    def books(self):
        """Return a list of comma separated list of books by the author"""
        pass

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

Maybe I could do a filter query to get books by a particular author but it doesn't seem like the django way to do it? I'm also not sure how to pass the filter function a python object rather than text.

Thanks

Upvotes: 2

Views: 233

Answers (1)

second
second

Reputation: 28637

when you define a foreignkey or manytomany field, django sets up a reverse relation for you, which in your case is book_set. so something like:

def books(self):
    books = self.book_set.all()
    return ', '.join([book.title for book in books])

see related objects in the docs

Upvotes: 4

Related Questions