Last active
December 20, 2017 15:54
-
-
Save Deepwalker/49e25496768483a825b3020a84c74ec1 to your computer and use it in GitHub Desktop.
Custom joins for django. Probably works with 1.11 and 2.x.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CustomFromSQL(object): | |
def __init__(self, sql): | |
self.sql = sql | |
def as_sql(self, compiler, connection): | |
return self.sql, [] | |
def add_to_queryset(self, queryset): | |
alias = hash(self.sql) | |
# Django iterates over query.tables | |
queryset.query.tables.append(alias) | |
# checking that query has references to this table | |
queryset.query.alias_refcount[alias] = 1 | |
# and take froms and joins from query.alias_map | |
queryset.query.alias_map[alias] = self | |
def test_custom_join(): | |
qs = User.objects.filter(age__gt=18) | |
custom_join = CustomFromSQL('JOIN user AS user2 ON user2.gender <> user.gender AND user2.age == user.age') | |
custom_join.add_to_queryset(qs) | |
return qs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment