FAQ: Databases and models

How can I see the raw SQL queries Django is running?

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

  1. >>> from django.db import connection
  2. >>> connection.queries
  3. [{'sql': 'SELECT polls_polls.id, polls_polls.question, polls_polls.pub_date FROM polls_polls',
  4. '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 hasthe following:

  1. ``sql`` -- The raw SQL statement
  2. ``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 thesame interface on each member of the connections dictionary:

  1. >>> from django.db import connections
  2. >>> 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:

  1. from django.db import reset_queries
  2. reset_queries()

Can I use Django with a pre-existing database?

Yes. See Integrating with a legacy database.

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

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

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

Do Django models support multiple-column primary keys?

No. Only single-column primary keys are supported.

But this isn’t an issue in practice, because there’s nothing stopping you fromadding other constraints (using the unique_together model option orcreating the constraint directly in your database), and enforcing theuniqueness at that level. Single-column primary keys are needed for things suchas the admin interface to work; e.g., you need a single value to specifyan object to edit or delete.

Does Django support NoSQL databases?

NoSQL databases are not officially supported by Django itself. There are,however, a number of side project and forks which allow NoSQL functionality inDjango, like Django non-rel.

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

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

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

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

  1. ALTER TABLE myapp_mytable ENGINE=MyISAM;