Skip to content

Instantly share code, notes, and snippets.

@quevon24
Created April 11, 2023 20:27
Show Gist options
  • Save quevon24/186dc5f87f6aef969bb8bb79448efa2a to your computer and use it in GitHub Desktop.
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
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