12

I want to fire up the django shell with a temporary database (like what's done when doing django tests)

Is there any command like:

python manage.py testshell

where I can create a bunch of bogus models without polluting my database?

Ben
  • 6,986
  • 6
  • 44
  • 71
  • IIRC, the unit testing framework creates the test DB for you. You just have to make sure it has the right permissions to do so. – Mike DeSimone Jun 01 '14 at 02:17

2 Answers2

21

Nevermind, this blog post explains it

>>> from django import test
>>> test.utils.setup_test_environment() # Setup the environment
>>> from django.db import connection
>>> db = connection.creation.create_test_db() # Create the test db
Ben
  • 6,986
  • 6
  • 44
  • 71
  • Even though you answered it yourself, mark this answer as correct so this doesn't show up as an unanswered question. – Mike DeSimone Jun 01 '14 at 02:18
  • 2
    @MikeDeSimone I have 2 more days until I can do that, but will do. – Ben Jun 01 '14 at 02:24
  • Ah, forgot about the delay. – Mike DeSimone Jun 01 '14 at 03:59
  • 1
    The blog link is invalid, but I think the commands are adequate for a test shell. Maybe the two commands `connection.creation.destroy_test_db()` and `test.utils.tear_down_test_environment()` are also helpful. – motam May 03 '16 at 05:20
  • Use `db = connection.creation.create_test_db(keepdb=True)` if you want to connect to an existing database and you're using Django >= 1.8. Docs are [here](https://docs.djangoproject.com/en/2.0/topics/testing/advanced/#django-db-connection-creation). – Shaun Overton Apr 17 '18 at 19:43
-2

You could just turn autocommit off:

from django.db import transaction
transaction.set_autocommit(False)
blueyed
  • 27,102
  • 4
  • 75
  • 71