Skip to content

Instantly share code, notes, and snippets.

@malinich
Created August 8, 2016 06:14
Show Gist options
  • Save malinich/ce7492aa902d68138245eb66b875ee6d to your computer and use it in GitHub Desktop.
Save malinich/ce7492aa902d68138245eb66b875ee6d to your computer and use it in GitHub Desktop.
def join_to(self, table1, table2, field1, field2, queryset, alias='', left=True):
def extra_join_cond(where_class, alias, related_alias):
if (alias, related_alias) == ('[sys].[columns]',
'[sys].[database_permissions]'):
where = '[sys].[columns].[column_id] = ' \
'[sys].[database_permissions].[minor_id]'
children = [ExtraWhere([where], ())]
wh = where_class(children)
return wh
return None
dpj = ForeignObject(
to=table2,
on_delete=lambda: None,
from_fields=[None],
to_fields=[None],
rel=None,
related_name=None
)
dpj.opts = Options(table1._meta)
dpj.opts.model = table1
dpj.get_joining_columns = lambda: ((field1, field2),)
dpj.get_extra_restriction = extra_join_cond
is_left_join = True if left else False
dj = Join(table2._meta.db_table, table1._meta.db_table, 'T', "JOIN", dpj, is_left_join)
ac = queryset._clone()
ac.query.join(dj)
alias and setattr(dj, 'table_alias', alias)
return ac
# example of usecase
q = Principals.objects.using(db_name).filter(type__in=["'S'", "'U'", "'G'", "'R'", "'A'"])
.annotate(
UserName=Case(When(server_name=None,
then=CastFunc(account_name_, output_field=CharField())),
default=CastFunc(server_name_, output_field=CharField()),
output_field=CharField()),
Grantor=Col('T10', DatabasePrincipals._meta.get_field('name'),
output_field=CharField()))
... other fields
)
ac = self.join_to(DatabasePrincipals, ServerPrincipals, 'sid', 'sid', q)
ac = self.join_to(DatabasePermissions, DatabasePrincipals, 'grantor_principal_id', 'principal_id', ac, 'T10')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment