Sorry if this is too trivial but I have looked through the docs and
could not find a clear answer.

Given that I have a Book model with a ManyToManyField called authors
how do I get all the books for a particular author? Each book may have
more than one author, so I cannot filter the books using the standard
methods.

My models are:
class Author(models.Model):
    name = models.CharField(max_length=124)

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

If I got it right, according to the documentation to get to a 'child'
queryset I have to iterate with 'for each b in Book.objects.all()',
and then call the b.authors.all() on each instance in order to check
if a particular author.id is found in the authors queryset. But how do
I get the results as a queryset? I could not get this to work.

To get all the books for a given author.id, I have tried:

def books_by_author(request, object_id):
    '''does not work'''
    filtered_by_author = []
    for b in Book.objects.all():
        if object_id in [a.id for a in b.authors.all()]:
            filtered_by_author.append(b)
    return render_to_response('polls/book_list.html', {'object_list':
filtered_by_author,} )

But this, of course, does not work, because it returns a list and not
a query set. What would be a proper, nice solution?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to