Stevy
Stevy

Reputation: 3387

Django filter manytomanyfield exclude objects that are related to another model

I have 2 models, File and Fileset:

class File(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)


class Fileset(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)
    files = models.ManyToManyField(File, related_name='fileset_files')

I want to filter File objects that are not related to any other Fileset

Problem

Consider that I have 3 File objects:

I have 2 Fileset objects:

When I try the query:

File.objects
.filter(fileset_files__fileset_name='Fileset2')  # all files from Fileset2
.exclude(fileset_files=Fileset.objects.get(fileset_name='Fileset1'))  # exclude the files that are in Fileset1   

This returns File2 & File3 like I want.

How do I make this work when I have, lets say 20 different Filesets? How should I filter for Files that are in other Filesets when I have multiple Filesets?

Upvotes: 1

Views: 84

Answers (1)

Stevy
Stevy

Reputation: 3387

I solved it by using annotate and Count like this:

from django.db.models import Count

File.objects
.annotate(fileset_count=Count('fileset_files__uuid'))
.filter(fileset_count=1)

Upvotes: 1

Related Questions