[EMAIL PROTECTED] wrote:
> That works easily when you're just looking up one Tag. What I'm trying
> to figure out is the best way to search for multiple tags and return
> only the Posts common to all of those tags:

Joe,

My bad. I misunderstood your question. I think the only way to do this
(in SQL) is with a subselect or with multiple joins to the same table,
neither of which are possible in the direct DB API. But you can use the
extra() method to get around some of the constraints.

To solve your specific problem, I started with the custom SQL:

    select slug from blog_post
    where id in (select post_id from blog_post_tags
        where tag_id in ('programming', 'finance'))

This can be implemented in Django as:

>>> from danet.blog.models import Post, Tag
>>> Post.objects.all().extra(where=["blog_post.id in (select post_id from 
>>> blog_post_tags where tag_id in ('programming', 'finance'))"])
[<Post: Probability and Expectation>, <Post: ASP.NET 2.0>, <Post: Code
Highlight
ing>]
>>>

So I've just copied the where-clause from the SQL (and explicitly
qualified the id column with 'blog_post.id').

Its debatable whether this is an improvement over direct SQL. You could
just as easily do

>>> from django.db import connection
>>> cursor = connection.cursor()
>>> cursor.execute("select post_id from blog_post_tags where tag_id in ('program
ming', 'finance')")
3L
>>> Post.objects.in_bulk([row[0] for row in cursor.fetchall()])
{16L: <Post: Probability and Expectation>, 1L: <Post: ASP.NET 2.0>, 6L:
<Post: C
ode Highlighting>}
>>>

In either case you've got about the same amount of custom SQL in your
Python code so its really a six-of-one situation.
-Dave


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to