Django's ManyToMany Link "Contains"

I am creating a small task manager, all tasks have shortcuts. I need to select all tasks with multiple shortcuts. At the moment, I do:

    tasks = Task.objects.all().filter(labels__in=label_list).distinct()

      

which returns all tasks where at least one label is also in the label list, but I only want the tasks that have all the labels that are in the label_list.

More precise example: if I go through ['1', '2'] as label_list, I don't want to return all issues with label 1 OR

label 2 (this is what happens now), but want all Issues with label 1 to AND

be displayed mark 2.

I want the labeled tables to contain

Relationship binding label means:

class Task(models.Model):
    ....
    labels = models.ManyToManyField(Label, null=True, blank = True)
    ....

      

+3


source to share


1 answer


This is achieved outside of the django ORM, but you can try:

labels = ['1', '2']
qs = Task.objects.all()
for label in labels:
    qs = qs.filter(labels=label).distinct()

      



Obviously quite ugly, and would be a rather expensive operation for a long list of shortcuts, but it might work for you.

Alternatively, you can check out django-taggit which is a mature django annotation app that provides similar functionality to "label". They handle the "contains" issue using the original SQL.

+1


source







All Articles