FAQ: Databases and modelsLink to this heading

How can I see the raw SQL queries Django is running?Link to this heading

Make sure your Django DEBUG setting is set to True. Then do this:

Python console
>>> from django.db import connection
>>> connection.queries
[{'sql': 'SELECT polls_polls.id, polls_polls.question, polls_polls.pub_date FROM polls_polls',
'time': '0.002'}]

connection.queries is only available if DEBUG is True. It’s a list of dictionaries in order of query execution. Each dictionary has the following:

  • sql - The raw SQL statement

  • time - How long the statement took to execute, in seconds.

connection.queries includes all SQL statements – INSERTs, UPDATES, SELECTs, etc. Each time your app hits the database, the query will be recorded.

If you are using multiple databases, you can use the same interface on each member of the connections dictionary:

Python console
>>> from django.db import connections
>>> connections["my_db_alias"].queries

If you need to clear the query list manually at any point in your functions, call reset_queries(), like this:

Code
from django.db import reset_queries

reset_queries()

Can I use Django with a preexisting database?Link to this heading

Yes. See Integrating with a legacy database.

If I make changes to a model, how do I update the database?Link to this heading

Take a look at Django’s support for schema migrations.

If you don’t mind clearing data, your project’s manage.py utility has a flush option to reset the database to the state it was in immediately after migrate was executed.

Do Django models support multiple-column primary keys?Link to this heading

Partially. See Composite primary keys.

Does Django support NoSQL databases?Link to this heading

NoSQL databases are not officially supported by Django itself. There are, however, a number of side projects and forks which allow NoSQL functionality in Django.

You can take a look on the wiki page which discusses some projects.

How do I add database-specific options to my CREATE TABLE statements, such as specifying MyISAM as the table type?Link to this heading

We try to avoid adding special cases in the Django code to accommodate all the database-specific options such as table type, etc. If you’d like to use any of these options, create a migration with a RunSQL operation that contains ALTER TABLE statements that do what you want to do.

For example, if you’re using MySQL and want your tables to use the MyISAM table type, use the following SQL:

SQL
ALTER TABLE myapp_mytable ENGINE=MyISAM;