Skip to content

Instantly share code, notes, and snippets.

@simonw
Last active April 20, 2024 18:34
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save simonw/30d2e626772e84edd688ba717a766c89 to your computer and use it in GitHub Desktop.
Save simonw/30d2e626772e84edd688ba717a766c89 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',
)
)
@simonw
Copy link
Author

simonw commented Jun 28, 2016

Here's the SQL this generates (at least for MySQL):

UPDATE `myapp_mymodel`
    SET `description` = replace(`myapp_mymodel`.`description`, '\r\n', '\n')
    WHERE `myapp_mymodel`.`description` LIKE '%\r\n%'

@czpython
Copy link

This was quite helpful. Thanks!

@tobiasmcnulty
Copy link

Agreed, many thanks!

@oleksandrzelentsov
Copy link

thank you, man, it's pretty cool!

@Iazzetta
Copy link

Iazzetta commented Mar 4, 2020

thank you!

@ruohola
Copy link

ruohola commented Dec 6, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment