Represent a wrapped value as a node within an expression.
| 1146 | |
| 1147 | @deconstructible(path="django.db.models.Value") |
| 1148 | class Value(Expression): |
| 1149 | """Represent a wrapped value as a node within an expression.""" |
| 1150 | |
| 1151 | # Provide a default value for `for_save` in order to allow unresolved |
| 1152 | # instances to be compiled until a decision is taken in #25425. |
| 1153 | for_save = False |
| 1154 | allowed_default = True |
| 1155 | |
| 1156 | def __init__(self, value, output_field=None): |
| 1157 | """ |
| 1158 | Arguments: |
| 1159 | * value: the value this expression represents. The value will be |
| 1160 | added into the sql parameter list and properly quoted. |
| 1161 | |
| 1162 | * output_field: an instance of the model field type that this |
| 1163 | expression will return, such as IntegerField() or CharField(). |
| 1164 | """ |
| 1165 | super().__init__(output_field=output_field) |
| 1166 | self.value = value |
| 1167 | |
| 1168 | def __repr__(self): |
| 1169 | return f"{self.__class__.__name__}({self.value!r})" |
| 1170 | |
| 1171 | def as_sql(self, compiler, connection): |
| 1172 | connection.ops.check_expression_support(self) |
| 1173 | val = self.value |
| 1174 | output_field = self._output_field_or_none |
| 1175 | if output_field is not None: |
| 1176 | if self.for_save: |
| 1177 | val = output_field.get_db_prep_save(val, connection=connection) |
| 1178 | else: |
| 1179 | val = output_field.get_db_prep_value(val, connection=connection) |
| 1180 | try: |
| 1181 | get_placeholder_sql = output_field.get_placeholder_sql |
| 1182 | except AttributeError: |
| 1183 | pass |
| 1184 | else: |
| 1185 | return get_placeholder_sql(val, compiler, connection) |
| 1186 | if val is None: |
| 1187 | # oracledb does not always convert None to the appropriate |
| 1188 | # NULL type (like in case expressions using numbers), so we |
| 1189 | # use a literal SQL NULL |
| 1190 | return "NULL", () |
| 1191 | return "%s", (val,) |
| 1192 | |
| 1193 | def as_sqlite(self, compiler, connection, **extra_context): |
| 1194 | sql, params = self.as_sql(compiler, connection, **extra_context) |
| 1195 | try: |
| 1196 | if self.output_field.get_internal_type() == "DecimalField": |
| 1197 | if isinstance(self.value, Decimal): |
| 1198 | sql = "(CAST(%s AS REAL))" % sql |
| 1199 | else: |
| 1200 | sql = "(CAST(%s AS NUMERIC))" % sql |
| 1201 | except FieldError: |
| 1202 | pass |
| 1203 | return sql, params |
| 1204 | |
| 1205 | def resolve_expression( |
no outgoing calls