On Thu, Jun 30, 2011 at 08:19:36AM -0700, peroksid wrote:
> Hi.
> 
> Queryset attribute query has method join() which allows to explicitly
> make JOINs. First argument passed to this method is a tuple of left
> table, right table, left column and right column, and rest of
> arguments define if we have LEFT OUTER or INNER join. Arguments from
> the tuple are used to create an "ON" expression like
> left_table.left_column=right_table.right_column.
> 
> I need to have for the "ON" expression slighlty more complex
> expression, something like
> "left_table.left_column=right_table.right_column AND
> right_table.another_column=42". Method join() obviously  can not be
> used for this purpose because it tuple defining join connection
> consists off 4 elements.
> I suspect there is no way to create such a double join condition at
> all, event without constant involved instead of column.
> 
> Tinkering with query does not promise anything here.
> I could be happy with replacing a part of resulting SQL query before
> it is sent to the database.
> Is there a way to filter text of SQL query somewhere before it is
> executed?

I hope you realize this is deep ORM black magic you're messing with.
(-:

Anyway, as for your problem, if the query is otherwise simple enough
that you can know for sure what alias "right_table" gets, you can
hijack this using QuerySet.extra to add a filter on this table.

Another idea might be to look at the implementation of
GenericForeignKeys. You'll notice a method, extra_filters, which is
used in reverse generic relation traversals. This is used to add a
very similar extra filter to a join, in this case limiting the query
to a single content type.

To use this feature, you'd have to create a subclass of the field used
by right_table.right_column to implement this. Then a regular lookup
spanning this field (assuming it is a relationship field) would
trigger its extra_filters. Note however, this is pretty much limited,
you'd probably have to apply a fair bit of logic inside this method
(unless this kind of join is the only one you want to make on this
field) and is subject to change. More specifically, it is still
possible I'll have to modify its behavior as part of my work on
composite fields.

Anyway, should you use either possibility, the extra filter won't be
part of the join condition, rather it will appear in the WHERE clause.
That shouldn't matter much, though.

Hope this will help you.

Michal

Attachment: signature.asc
Description: Digital signature

Reply via email to