Created
April 11, 2023 20:27
-
-
Save quevon24/186dc5f87f6aef969bb8bb79448efa2a to your computer and use it in GitHub Desktop.
Django Function to remove characters from column, keep only number and cast it as integer
This file contains 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
class ExtractInteger(Func): | |
"""Returns the first int value from the string. Note that this | |
requires the string to have an integer value inside. | |
Example of usage: | |
YourModel.objects.filter(something=True).annotate(integer_value=ExtractInteger("field_name")).order_by("-integer_value") | |
""" | |
function = "REGEXP_MATCH" | |
template = "CAST((%(function)s(%(expressions)s, '\d+'))[1] as INTEGER)" | |
output_field = IntegerField() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment