Do a database query to check if the expressions of the Q instance matches against the expressions.
(self, against, using=DEFAULT_DB_ALIAS)
| 169 | yield child |
| 170 | |
| 171 | def check(self, against, using=DEFAULT_DB_ALIAS): |
| 172 | """ |
| 173 | Do a database query to check if the expressions of the Q instance |
| 174 | matches against the expressions. |
| 175 | """ |
| 176 | # Avoid circular imports. |
| 177 | from django.db.models import Value |
| 178 | from django.db.models.sql import Query |
| 179 | from django.db.models.sql.constants import SINGLE |
| 180 | |
| 181 | query = Query(None) |
| 182 | for name, value in against.items(): |
| 183 | if not hasattr(value, "resolve_expression"): |
| 184 | value = Value(value) |
| 185 | query.add_annotation(value, name, select=False) |
| 186 | query.add_annotation(Value(1), "_check") |
| 187 | connection = connections[using] |
| 188 | # This will raise a FieldError if a field is missing in "against". |
| 189 | query.add_q(self) |
| 190 | compiler = query.get_compiler(using=using) |
| 191 | context_manager = ( |
| 192 | transaction.atomic(using=using) |
| 193 | if connection.in_atomic_block |
| 194 | else nullcontext() |
| 195 | ) |
| 196 | try: |
| 197 | with context_manager: |
| 198 | return compiler.execute_sql(SINGLE) is not None |
| 199 | except DatabaseError as e: |
| 200 | logger.warning("Got a database error calling check() on %r: %s", self, e) |
| 201 | return True |
| 202 | |
| 203 | def deconstruct(self): |
| 204 | path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) |