def check(self, against, using=DEFAULT_DB_ALIAS): """ Do a database query to check if the expressions of the Q instance matches against the expressions. """ # Avoid circular imports. from django.db.models import Value from django.db.models.sql import Query from django.db.models.sql.constants import SINGLE query = Query(None) for name, value in against.items(): if not hasattr(value, "resolve_expression"): value = Value(value) query.add_annotation(value, name, select=False) query.add_annotation(Value(1), "_check") # This will raise a FieldError if a field is missing in "against". query.add_q(self) compiler = query.get_compiler(using=using) try: return compiler.execute_sql(SINGLE) is not None except DatabaseError as e: logger.warning("Got a database error calling check() on %r: %s", self, e) return True
def _get_check_sql(self, model, schema_editor): query = Query(model=model) # Add annotations for k, v in self.annotations.items(): query.add_annotation(v, k) where = query.build_where(self.check) compiler = query.get_compiler(connection=schema_editor.connection) sql, params = where.as_sql(compiler, schema_editor.connection) return sql % tuple(schema_editor.quote_value(p) for p in params)