MistyD
MistyD

Reputation: 17243

QuerySet results being duplicated when chaining queries

So I am attempting to chain queries together. This is what I am doing

 queryset_list = modelEmployee.objects.filter(stars__lte=3)
 A = len(queryset_list) #A=2
 queryset_list = queryset_list.filter(skills__skill_description__in=skill_filter)
 A = len(queryset_list) #A=4

So with the above I am suppose to get two results but I am getting four. Seems like the results of first query are being duplicated in the second thus resulting to 4. Any suggestion on why the results are being duplicated and how I can fix this ? I was expecting to get only two items since it passes both the filters.

This is the model

class modelEmployee(models.Model):
    user                = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    skills              = models.ManyToManyField(modelSkill, blank=True)
    location            = models.PointField(srid=4326,max_length=40, blank=True,null=True)

Upvotes: 3

Views: 291

Answers (1)

Bernhard Vallant
Bernhard Vallant

Reputation: 50796

If you do a query on a ManyToManyField Django will perform an INNER JOIN which means there will be a row for every item on each side of the join. If you want to have unique results use distinct().

queryset_list = queryset_list.filter(
    skills__skill_description__in=skill_filter
).distinct()

See this article for some examples.

Upvotes: 3

Related Questions