[Django]-How to use default database in django testing

2👍

✅

use the same database name for your default and test.

django uses the following pattern to define databases:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'mydatabaseuser',
        'NAME': 'mydatabase',
        'TEST': {
            'NAME': 'mytestdatabase',
        },
    },
}

just use mydatabase instead of mytestdatabase

6👍

Another option would be to use Django’s database fixtures for the data that is common to all of your environments (test, dev, prod). The added benefit here is that fixtures make it easy to seed a new database with your common data:

./manage.py loaddata myfixture1 myfixture2

You can create fixures with ./manage.py dumpdata. Here’s how to create a JSON fixture from a model called Author in the books app, for example:

mkdir books/fixtures
./manage.py dumpdata --indent=2 --output books/fixtures/author.json books.author 

Then you can use that fixture in your tests:

from django.test import TestCase


class AuthorTestCase(TestCase):
    fixtures = ['author']
    ....

Leave a comment