Skip to content

Commit bc01a28

Browse files
committed
Added documentation example how to create the test database from a sql
script. Refs #343.
1 parent 3aaaaa0 commit bc01a28

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

docs/database.rst

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,3 +400,29 @@ Put this in ``conftest.py``::
400400
cur = connection.cursor()
401401
cur.execute('ALTER SEQUENCE app_model_id_seq RESTART WITH %s;',
402402
[random.randint(10000, 20000)])
403+
404+
Create the test database from a custom SQL script
405+
"""""""""""""""""""""""""""""""""""""""""""""""""
406+
407+
You can replace the :fixture:`django_db_setup` fixture and run any code in its
408+
place. This includes creating your database by hand by running a SQL script
409+
directly. This example shows how sqlite3's executescript method. In more a more
410+
general use cases you probably want to load the SQL statements from a file or
411+
invoke the ``psql`` or the ``mysql`` command line tool.
412+
413+
Put this in ``conftest.py``::
414+
415+
import pytest
416+
from django.db import connection
417+
418+
419+
@pytest.fixture(scope='session')
420+
def django_db_setup(django_db_blocker):
421+
with django_db_blocker:
422+
with connection.cursor() as c:
423+
c.executescript('''
424+
DROP TABLE IF EXISTS theapp_item;
425+
CREATE TABLE theapp_item (id, name);
426+
INSERT INTO theapp_item (name) VALUES ('created from a sql script');
427+
''')
428+

0 commit comments

Comments
 (0)