Search code examples
djangodjango-modelsmany-to-many

Django How To Query ManyToMany Relationship Where All Objects Match


I have the following models:

## Tags for issues
class issueTags(models.Model):
    name = models.CharField(max_length=400)
class issues(models.Model):
    tags = models.ManyToManyField(issueTags,blank = True)

In my view I get an array from some client side JavaScript i.e.

(Pdb) array_data = request.POST['arr']
(Pdb) array_data
'["2","3"]'

How should I filter my issues object to find all issues which match all tags in the array? (the 2,3 are the ID values for tag__id.

If there is a better way to arrange the objects that would also work so I can search in this fashion.


Solution

  • It isn't most elegant solution or pythonic but I ended up just looping around the resulting filter.

    def filter_on_category(issue_object,array_of_tags):
        #keep filtering to make an and
        i = 0
        current_filter = issue_object
        while (i < (len(array_of_tags))):
            #lets filter again
            current_filter=current_filter.filter(tags__id__in=array_of_tags[i])
            i=i+1
    
        return current_filter