Skip to content

Instantly share code, notes, and snippets.

@philgyford
Created January 5, 2018 11:56
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 philgyford/d059a0a1dbddac15c1ff9be94f669682 to your computer and use it in GitHub Desktop.
Save philgyford/d059a0a1dbddac15c1ff9be94f669682 to your computer and use it in GitHub Desktop.
Find and replace text in Django objects' fields

Django Find and Replace

This was used to replace all the instances of old Media URLs with new ones, but could be used for any kind of text search/replace across Django objects.

  1. Change the model import to whatever your app and model is.
  2. Set the to_find and to_replace strings to whatever you need.
  3. Change Post to your model name, and the fields to whatever field(s) you want to search and replace across.

I pasted all this into the Django shell to run it as I only needed it once.

To run it again you can then just change to_find and to_replace and run the same Post.objects.update... again.

from django.db.models import F, Func, Value
from weblogs.models import Post
to_find = 'src="http://www.exmample.org/my/old/path/'
to_replace = 'src="https://my-new-bucket.s3.amazonaws.com/media/'
def replace_func(field_name, find_str, replace_str):
return Func(
F(field_name),
Value(find_str), Value(replace_str),
function='replace'
)
Post.objects.update(
excerpt = replace_func('excerpt', to_find, to_replace),
body = replace_func('body', to_find, to_replace),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment