Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sanyambansal76/5765d4a707e6cf5ee814cd47b21d9c8a to your computer and use it in GitHub Desktop.
Save Sanyambansal76/5765d4a707e6cf5ee814cd47b21d9c8a to your computer and use it in GitHub Desktop.
How to use the SQL replace function in a Django ORM query
from django.db.models import F, Func, Value
from myapp.models import MyModel
# Annotation
MyModel.objects.filter(description__icontains='\r\n').annotate(
fixed_description=Func(
F('description'),
Value('\r\n'), Value('\n'),
function='replace',
)
)
# Bulk replace/fix
MyModel.objects.filter(description__icontains='\r\n').update(
description=Func(
F('description'),
Value('\r\n'), Value('\n'),
function='replace',
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment