For the sake of example, I have the following Django models:
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Book(models.Model):
name = models.CharField(max_length=30)
authors = models.ManyToManyField(Author)
(because books regularly have multiple authors, and authors regularly write multiple books)
Now say I have a list of authors' names as tuples:
author_list = [('clarke', 'arthur'), ('herbert', 'frank'), ('asimov', 'isaac')]
Is there a way to query for all Books whose authors
m2m field has at least one Author
instance that satisfies
author.last_name = pair[0]
author.first_name = pair[1]
for some pair in author_list? I.e. to get all books contributed to by at least one of a given list of authors?
The query I *want* to write looks like this:
Book.objects.filter(
authors__first_name__in=[pair[1] for pair in author_list],
authors__last_name__in=[pair[0] for pair in author_list]
)
but that doesn't work, because then all permutations (Arthur Herbert, Frank Asimov, Isaac Clarke, etc...) are allowed. But I'm not sure how to say, essentially:
'Select all books who have an author that satisfies these two things at once.'
or really:
'Select all books who have an author whose pair of (last_name, first_name) is in this list of tuples.'
Is there a clean way to do that search in django?