Last active
January 22, 2025 18:12
-
-
Save simonw/30d2e626772e84edd688ba717a766c89 to your computer and use it in GitHub Desktop.
How to use the SQL replace function in a Django ORM query
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
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', | |
) | |
) |
This was quite helpful. Thanks!
Agreed, many thanks!
thank you, man, it's pretty cool!
thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's the SQL this generates (at least for MySQL):