Created
November 18, 2025 17:15
-
-
Save EnriqueSoria/ff09cdfe007a0380add58d9331b7523d to your computer and use it in GitHub Desktop.
Extract and cast values from a `TextField` or `JSONField` (in Django)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from django.db.models import CharField | |
| from django.db.models import Func | |
| from django.db.models import Value | |
| from django.db.models.functions import Cast | |
| class JSONExtractAndCast(Cast): | |
| def __init__(self, expression, *paths, output_field): | |
| # borrowed from django_mysql.models.functions.JSONExtract | |
| exprs = [expression] | |
| for path in paths: | |
| if not hasattr(path, "resolve_expression"): | |
| path = Value(path) | |
| exprs.append(path) | |
| extracted_value = Func( | |
| *exprs, | |
| function="JSON_EXTRACT", | |
| output_field=CharField(), | |
| ) | |
| unquoted_value = Func( | |
| extracted_value, | |
| function="JSON_UNQUOTE", | |
| output_field=output_field, | |
| ) | |
| super().__init__(unquoted_value, output_field=output_field) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment