There are 2 models connected with a many-to-many relationship.
class Record():
working_on_record = models.ManyToManyField(
UserProfile, related_name="working_on_record", blank=True)
class UserProfile():
name = CharField...
The UserProfile is just a basic user model.
Now I want to query a search for records and check if all keywords are matched but if I do:
query = Q()
c1 = UserProfile.objects.filter(name__icontains='peter')
query.add(Q(working_on_record__in=c1), Q.AND)
c2 = UserProfile.objects.filter(name__icontains='john')
query.add(Q(working_on_record__in=c2), Q.AND)
set3 = list(models.Record.objects.filter(query))
Set3 is empty, despite there is a record which has two people working on it whose names are "john smith" and "peter parker". If I replace "john" in c2 by "parker" I get all records where "peter parker" is working on it.
But if I chain the filter methods:
set4 = list(models.Record.objects
.filter(working_on_record__in=c1)
.filter(working_on_record__in=c2)
)
set4 is not empty and contains the record I want.
Is it possible to change the Q-query so that I get the behavior I want? Is it possible to filter with a Q-query on one many-to-many-relationship with different values from different objects connected with an AND?
I don't like the idea of chaining the filter methods, because of multiple possible usages of the Q-query, so I would have to iterate at multiple occasions through all queries and chain them.