Peter Graham
Peter Graham

Reputation: 2575

Django Many to Many Query Set Filter

I'm able to query my database below to get the result that I want but I don't want to have to iterate through all of the author objects, just the ones that have more than one post. There is a many-to-many relationship between Authors and Posts with the Many-To-ManyField on the Post. Does anyone know how to make this more efficient?

for author in Author.objects.all():
    if len(author.post_set.all()) > 0:
        print author

Upvotes: 1

Views: 389

Answers (1)

knbk
knbk

Reputation: 53699

Use this:

for author in Author.objects.filter(post__isnull=False):
    print author

Upvotes: 2

Related Questions