On 8/22/06, Russell Keith-Magee <[EMAIL PROTECTED]> wrote:
> On 8/22/06, Alan Green <[EMAIL PROTECTED]> wrote:
> > Has anybody found a way to add an table to query with an outer join?

> It isn't really a documented feature, and I haven't worked through the
> details (so you will need to do a little code spelunking by yourself) but
> you might get some traction playing around with Q objects in
> django/db/models/query.py.

Thanks. This worked great. I made this class:

from django.db.models import Q
from django.utils.datastructures import SortedDict

class QLeftOuterJoin(Q):
    def __init__(self, alias, table, where):
        self.alias, self.table, self.where = alias, table, where

    def get_sql(self, opts):
        joins = SortedDict()
        joins[self.alias] = (self.table, 'LEFT OUTER JOIN', self.where)
        return (joins, [], [])

As you suggested, this can then be used as an arg to filter() like any
other Q object:

    queryset = queryset.filter(QLeftOuterJoin('rmr', "hr_reader_most_recent",
                "rmr.reader_id = hr_reader.id"))

> Although there is a base Q object, the only contractual obligation of that
> object is that it has a get_sql method that returns a tuple (joins, where,
> params). The 'joins' member is itself a list of tuples, each member being of
> the form (alias, (table, join_type, condition)).

I ended up having to extend Q anyway. The QAnd and QOr classes check
the type of with isinstance(), and they were raising a TypeError
exception.

> Like I said - I haven't tried this; if it breaks, you get to keep every
> single one of the pieces :-)

And if anyone uses the above QLeftOuterJoin class, and it breaks their
program, they get to keep all the pieces too.

Thanks again - this has helped me tidy up a nasty, mess patch in my code.

Cheers,

Alan.

-- 
Alan Green
[EMAIL PROTECTED] - http://bright-green.com

--~--~---------~--~----~------------~-------~--~----~
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