I'm quite newbie in Django. I have an application in project which is developed with test driven development. In production we use MySQL as database engine, but if I run test with MySQL:
./manage test myapp
Then it absorbs too much time (2-4 mins) to create database, althought tests are quite fast (about a second).
If I use SQLite then tests requires only a few seconds, which is perfect for me. But the problem is that I often need the admin interface with my local database on MySQL.
How to make django to run tests on sqlite and launch runserver with mysql?
Now I use these settings in settings/local.py, but I should comment/uncomment lines to change database depending on what activity I do at the moment.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Use for testing
'NAME': 'databasename.db3',
# 'ENGINE': 'django.db.backends.mysql', # Use if need admin on localserver
# 'NAME': 'databasename',
'USER': 'myuser', # Not used with sqlite3.
'PASSWORD': 'somepassword', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
'TEST_CHARSET': "utf8", #option to make tesing database with utf8
'TEST_COLLATION': "utf8_general_ci",
}
}
Django's admin doesn't have any explicit support for multiple databases. If you want to provide an admin interface for a model on a database other than that specified by your router chain, you'll need to write custom ModelAdmin classes that will direct the admin to use a specific database for content.
Django officially supports the following databases: PostgreSQL. MariaDB. MySQL.
The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.
One option would be to check sys.argv
for the test
argument in settings.py
:
if 'test' in sys.argv:
DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
DATABASES['default']['NAME'] = 'databasename.db3'
Though, as a side note: strictly speaking, it is not really a good idea to have different database backends for testing and for development/stage/production. You may encounter database-specific "special" cases, that can cost you a lot of time and headache.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With