如何在django测试中使用默认数据库

A.R*_*ouf 3 testing django django-rest-framework

现在我想使用默认数据库测试 API,因为我首先需要太多数据来模拟请求,所以我不想设置测试数据库

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'bills_db',
        'USER': 'root',
        'PASSWORD': '****',
    }
}
Run Code Online (Sandbox Code Playgroud)

我该如何使用它?

Fra*_*ney 6

另一种选择是使用Django 的数据库固定装置来存储所有环境(测试、开发、生产)通用的数据。这里的额外好处是,固定装置可以轻松地将常用数据植入新数据库:

./manage.py loaddata myfixture1 myfixture2
Run Code Online (Sandbox Code Playgroud)

您可以使用 创建装置./manage.py dumpdataAuthor以下是如何从应用程序中调用的模型创建 JSON 夹具books,例如:

mkdir books/fixtures
./manage.py dumpdata --indent=2 --output books/fixtures/author.json books.author 
Run Code Online (Sandbox Code Playgroud)

然后您可以在测试中使用该装置:

from django.test import TestCase


class AuthorTestCase(TestCase):
    fixtures = ['author']
    ....
Run Code Online (Sandbox Code Playgroud)