Opened 17 years ago

Closed 17 years ago

#4849 closed (duplicate)

Nested Filters

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

Description

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 by Collin Grady <cgrady@…>, 17 years ago

Component: Core frameworkDatabase wrapper

comment:2 by ben.stookey@…, 17 years ago

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 by nick.lane.au@…, 17 years ago

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 by ben.stookey@…, 17 years ago

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 by nick.lane.au@…, 17 years ago

Sorry, I see what you mean now.

comment:6 by Malcolm Tredinnick, 17 years ago

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 by Malcolm Tredinnick, 17 years ago

Resolution: duplicate
Status: newclosed

Dupe of #4464.

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