0

I've got a model that has a list of tags.

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d', max_length=150)
    tags = models.ManyToManyField(Tag)

I want to be able to find all the Documents that are tagged with X and Y, but not exclusively X and Y. That is, I want documents that are tagged with X, Y, Z to show up when I search for X and Y.

The accepted answer from this question gets me pretty far, but it returns items that are tagged with those and only those tags. The annotation limits the query set.

Community
  • 1
  • 1
ghiotion
  • 285
  • 5
  • 12

2 Answers2

1

Figured it out. There's a great resource on SO here. In my particular case, I wanted chained filters. This is how I did it with an arbitrary number of tags.

docs = Document.objects

for tag in tags:
    docs = docs.filter(tags=tag)

This gave me the AND query I needed.

Community
  • 1
  • 1
ghiotion
  • 285
  • 5
  • 12
0

You simply want an INNER JOIN - which is the default when you filter across relations.

This should do what you want:

Document.objects.filter(tags=X, tags=Y)

This gets you each Document which has both tag X and tag Y, regardless of any other tags.

knbk
  • 52,111
  • 9
  • 124
  • 122