On 17 December 2010 19:20, Jonas H. <jo...@lophus.org> wrote:
> Hello!
>
> Assuming the following data model:
>
> +------+                +------+                   +-----+
> | Blog | has many (1:n) | Post | tagged with (n:m) | Tag |
> +------+                +------+                   +-----+
>
> I want to filter out all blogs that have a post tagged with "foo" and "bar"
> (the same post satisfying *both* conditions).
>
> How would that query look like? Intuitively I'd say
>
>    Blog.objects.filter(post__tags__name="foo",
>                        post__tags__name="bar")
>
> but obviously that's a SyntaxError because of the repeated keyword argument
> to filter(). I also tried Q() objects but that generates some totally
> unrelated queries.

In [9]: print  Blog.objects.filter(Q(post__tags__name="foo") &
Q(post__tags__name="bar")).query

SELECT "simple_blog"."id"
    FROM "simple_blog"
        INNER JOIN "simple_post" ON ("simple_blog"."id" =
"simple_post"."blog_id")
        INNER JOIN "simple_post_tags" ON ("simple_post"."id" =
"simple_post_tags"."post_id")
        INNER JOIN "simple_tag" ON ("simple_post_tags"."tag_id" =
"simple_tag"."id")
    WHERE ("simple_tag"."name" = foo  AND "simple_tag"."name" = bar )

Looks related. It's exactly what you specified, but conditions you
gave are just impossible to satisfy.

Your task is a bit more complicated to do in SQL:

Blog.objects.filter(post_tags__name__in=["foo",
"bar"]).annotate(match_count=Count('post__tags')).filter(match_count=2)

This should give you the right results.

-- 
Łukasz Rekucki

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to