Search code examples
pythonruby-on-railsdjangosandbox

Django: running a python shell in a sandbox environment, similar to rails console --sandbox


Inside my Django project, I want to fire up a python shell wherein I can make simple changes to my database (saving new records, updating old ones, etc.) which are then automatically reverted back when I exit the shell. Essentially the same functionality as running:

rails console --sandbox

in a Ruby on Rails project. I'm not looking for all the features of a traditional sandbox such as blocking web-service calls, just the basic database rollback. Is this--or something similar--possible in Django?

I want to use this for testing purposes. I know I can use Django's testing infrastructure to do this, but there are some basic instances where this would be very useful (e.g. quickly confirming that a specific model functions the way I expect it to).


Solution

  • This is mostly done in python manage.py shell (or with django_extensions in INSTALLED_APPS better ... shell_plus) which is python command line from which you can manipulate the data and test some features you don't wan't to program before you test. Rollback in django shell is not possible as I know, but you can have separate settings.py with different DB settings so you will have another database where you can experiment in shell without corrupting your data.

    Here some sources:

    Django Best Practice: Settings file for multiple environments

    Django shell (from DJango docs)