Opened 9 years ago

Closed 9 years ago

#4849 closed (duplicate)

Nested Filters

Reported by: ben.stookey@… Owned by: Adrian Holovaty
Component: Database layer (models, ORM) Version: master
Severity: Keywords: filter, foreignkey
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


After review in #django I decided to post this as a bug.

3 and 4 should have the same output, shouldn't they?

>>> Article.objects.filter(tags=t1)   #1
[<Article: A1>, <Article: A2>]
>>> Article.objects.filter(tags=t2)   #2
[<Article: A1>]
>>> Article.objects.filter(tags=t1).filter(tags=t2)   #3
>>> Article.objects.filter(tags=t1, tags=t2)   #4
[<Article: A1>]

Although 4 works, the syntax doesn't allow for someone working with a list of tags.

Here are the models:

class Tag(models.Model):
	name = models.CharField(maxlength=32, unique=True)

class Article(models.Model):
	title = models.CharField(maxlength=255)
	tags = models.ManyToManyField(Tag)

Change History (7)

comment:1 Changed 9 years ago by Collin Grady <cgrady@…>

Component: Core frameworkDatabase wrapper

comment:2 Changed 9 years ago by ben.stookey@…

I guess 4 wasn't actually working either because I can't pass "tags" twice. It only looked at t2:

>>> Article.objects.filter(tags=t2, tags=t1)
[<Article: A1>, <Article: A2>]

comment:3 Changed 9 years ago by…

As you said, Article.objects.filter(tags=t2, tags=t1) won't work because you can't pass duplicate keyword arguments for "tags". For this you could use:

>>> Article.objects.filter(tags__in=(t1, t2)).distinct()
[<Article: A1>, <Article: A2>]

comment:4 Changed 9 years ago by ben.stookey@…

The problem is, that is an OR relationship and I'm looking for AND. Only those articles that have both tags. Shouldn't number 3 do that?

comment:5 Changed 9 years ago by…

Sorry, I see what you mean now.

comment:6 Changed 9 years ago by Malcolm Tredinnick

Triage Stage: UnreviewedAccepted

This is a known bug. I thought it was a duplicate of something, but I can't find it now. I'm back to working on the QuerySet rewrite, so it's something that gets fixed as part of that. Conjunctions involving the same column do not work at the moment.

comment:7 Changed 9 years ago by Malcolm Tredinnick

Resolution: duplicate
Status: newclosed

Dupe of #4464.

Note: See TracTickets for help on using tickets.
Back to Top