def q_mentioned_fields(q, model): """Returns list of field names mentioned in Q object. Q(a__isnull=True, b=F('c')) -> ['a', 'b', 'c'] """ query = Query(model) where = query._add_q(q, used_aliases=set(), allow_joins=False)[0] return list(sorted(set(expression_mentioned_fields(where))))
def q_to_sql(q, model, schema_editor): # Q -> SQL conversion based on code from Ian Foote's Check Constraints pull request: # https://github.com/django/django/pull/7615/ query = Query(model) where = query._add_q(q, used_aliases=set(), allow_joins=False)[0] connection = schema_editor.connection compiler = connection.ops.compiler('SQLCompiler')(query, connection, 'default') sql, params = where.as_sql(compiler, connection) params = tuple(map(schema_editor.quote_value, params)) where_sql = sql % params return where_sql