Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 403
MistyD Avatar asked Dec 01 '25 05:12

MistyD


1 Answers

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.

like image 78
Bernhard Vallant Avatar answered Dec 03 '25 22:12

Bernhard Vallant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!