Django bulk insert

Django bulk insert DEFAULT

Bulk Inserts Performance with Django and PostgreSQL

Using the Django ORM is often a productivity boon. It allows you to describe models and interact with your data in pure python code instead of mixing it with SQL queries. It removes the need for a lot of boilerplate by reducing the impedance mismatch between the persisted relational data and the object model used by the application.

The Django ORM also provides useful hooks that you can use to enforce models business logic. Custom save() methods and signals are guaranteed to run on every interaction with your model as long as you use the ORM.

These abstractions come with a performance cost. They work under the assumption that your code operates on records one by one. For example, save() is called on every single model instance, and signals receive one instance at a time.

When you only need to insert a few records into the database, this is not an issue. But when you need to save a batch of records, the performance cost of sending records to the database one by one is huge. Each round trip to the database has a fixed cost: a query needs to be sent to the database server which might be on a different machine. On top of that, the database can only see one request at a time and can't optimize multiple records creation. Sending a single request to create a batch of records minimizes the impact of the round trip to the server, and allows the database to batch the writes to the disk.

We can see how much the ORM can affect performance by running a simple benchmark. Each script starts from an empty database and inserts into the database 10,000 records of the following model:


It's a very simple model, with only three fields of three different types on top of the implicit id field. It has no foreign keys.

All the code used for this benchmark is available here. You can clone the repository and follow the instruction in the README to run the scripts yourself and reproduce the results presented here.

The Setup

The scripts were run using the following setup:

  • Operating System: Ubuntu 14.04
  • Database: PostgreSQL 9.3, using the default Ubuntu configuration
  • Database driver: psycopg2 2.6.1
  • Django 1.8.6
  • Hardware: Intel i5-4570S CPU, 16GB of RAM, Samsung 840 EVO SSD

The database and the python scripts were run on the same computer. This minimizes the cost of round trip time to the database, skewing the result in favor of non-batched operations. As we will see, despite this advantage the performance difference between non-batched and batched operations is still huge.

ORM create()

The more natural way to create records using the ORM is to create them one by one, using a simple loop:


This approach has several advantages: it's simple, easy to understand and respects all your custom model code.

Unfortunately, performance is poor:

$ python Created 10000 records in 12685ms

If you need to create lots of records, this kind of performance is often unacceptable.

ORM bulk_create()

Django does offer a method to handle exactly this scenario: bulk_create. You can pass it a list of new model instances to create, and it will issue bulk queries to the database:


The performance boost is huge:

$ python Created 10000 records in 334ms

Performance comes at a price: your custom save() method and signals won't be invoked. It also doesn't work with table inheritance.

In short, you can no longer trust the ORM to enforce your business logic, losing lots of the advantages of using an ORM in the first place.


Let's now turn away from the ORM to see if we can further improve performance using pure SQL queries.

A first, simple approach is to create records one by one using INSERT statements:

importutilsfromcontextlibimportclosingfromdjango.dbimportconnectionfromdjango.utilsimporttimezonedefsql_simple_insert(n_records):withclosing(connection.cursor())ascursor:foriinxrange(0,n_records):cursor.execute('INSERT INTO app_testmodel (field_1, field_2, field_3)''VALUES (%s, %s, %s)',(i,str(i),,)if__name__=='__main__':utils.timed(sql_simple_insert)

Similarly to the first ORM approach, creating records one by one performs poorly:

$ python Created 10000 records in 3968ms

It's about three times faster than creating records one by one using the ORM. That's how much the ORM abstractions are costing us. The queries sent to the database are the same, but the ORM needs to call custom validation and save methods and invoke all signals. It also needs to build the SQL insert query every single time.

Using SQL INSERT statements has the same disadvantage we saw with bulk_create, in that custom model business logic is not executed, but it only has a fraction of the performance gains.

SQL INSERT, using executemany

The psycopg2 cursor has a method to execute a single SQL statement multiple times, using a different set of arguments each time. It looks like a simple way to batch operations without changing the code too much:

importutilsfromcontextlibimportclosingfromdjango.dbimportconnectionfromdjango.utilsimporttimezonedefsql_simple_insert_executemany(n_records):withclosing(connection.cursor())ascursor:cursor.executemany('INSERT INTO app_testmodel (field_1, field_2, field_3)''VALUES (%s, %s, %s)',[(i,str(i),,n_records)],)if__name__=='__main__':utils.timed(sql_simple_insert_executemany)

Despite looking like a batch operation, performance didn't really improve:

$ python Created 10000 records in 3693ms

As it turns out, under the hood psycopg2 is still sending the queries one by one to the database. With that in mind, it's not surprising that performance is so close to the previous approach.


We can do a lot better by building a single SQL INSERT statement to create multiple records at once, similar to the SQL built by bulk_create:

importutilsfromcontextlibimportclosingfromdjango.dbimportconnectionfromdjango.utilsimporttimezonedefsql_batch_insert(n_records):sql='INSERT INTO app_testmodel (field_1, field_2, field_3) VALUES {}'.format(', '.join(['(%s, %s, %s)']*n_records),)params=[]foriinxrange(0,n_records):params.extend([i,str(i),])withclosing(connection.cursor())ascursor:cursor.execute(sql,params)if__name__=='__main__':utils.timed(sql_batch_insert)

Building the SQL query manually adds more noise to the code than using bulk_create, but other than that it has no significant disadvantage:

$ python Created 10000 records in 167ms

Performance is in the same order of magnitude as bulk_create, and as we saw when comparing the standard ORM create() method against simple SQL INSERT statements, the ORM overhead is non-trivial.


If we leave the realm of standard, portable SQL, PostgreSQL offers an extension to import and export records in bulk.

Using COPY FROM we can import data from a CSV file. The CSV file can also be read directly from the connection input stream. psycopg2 exposes this functionality in the cursor copy_from() method, which accepts any python file-like object to read the records from.

We can use StringIO together with the csv module to build this file-like object in memory, and then import it in the database using copy_from():


The code is relatively easy to understand and arguably more readable than the batch SQL INSERT query, but not as much as bulk_create. Performance is better than any of the other approaches:

$ python Created 10000 records in 96ms

We removed most of the overhead associated with creating and sending queries, and it shows. It's about three times faster than using the fastest ORM method.

This is possibly the more performant method to create multiple records in PostgreSQL.

Generating the data in the database

Finally, we can improve performance further by cheating. If we generate the data directly in the database, we don't need to send it across the wire, removing all the network overhead. On top of that, the database won't need to parse all the records data, since we're not actually sending any record.

This approach is not nearly as generic as the previous ones: in almost all practical cases, data has to come from somewhere (an external file, a web request, etc.) and is not automatically generated inside the database.

In some rare cases though, you do need to generate records programmatically with no external input and this approach can be used. Examples of that are static tables and denormalized tables automatically generated from other tables contents.

This approach also serves as a lower boundary on how fast we can hope to insert new records into the database, showing how close to optimal the previous methods were.

We can use GENERATE_SERIES to generate the 10000 records to insert:

importutilsfromcontextlibimportclosingfromdjango.dbimportconnectiondefgenerate_data_in_database(n_records):withclosing(connection.cursor())ascursor:cursor.execute(""" INSERT INTO app_testmodel (field_1, field_2, field_3) SELECT i, i::text, now() FROM generate_series(0, %s - 1) AS s(i) """,(n_records,),)if__name__=='__main__':utils.timed(generate_data_in_database)

Performance is obviously better than the previous approaches:

$ python Created 10000 records in 44ms

If you find yourself with a problem in which this approach can be used, by all means do so, because there is no faster way to insert new records.


The Django ORM design offers a good solution when you need to operate on a small set of records, which is the most common scenario in web applications. Using the hooks it provides can lead to readable, well encapsulated code.

On the other hand, as the number of records you need to operate on at once increases, the ORM becomes a performance liability.

If you took advantage of the hooks available in the ORM, and then you find yourself in a situation where you need to import a large amount of records, you will be in a tough spot.

You will need to decide between replacing all the custom model code with a batch friendly solution, or duplicating the necessary business logic in the code that inserts the records in batches. The first approach can be a lot of work if you have more than a handful of models and complex logic. The second one can be a good trade-off if you only need to batch load a small subset of the models, and their logic is simple, but duplicating logic can easily lead to inconsistencies, bugs, and duplicate maintenance effort.

Of course, if you can afford it, you can also decide to accept the performance impact, and insert records one by one.

As it often happens when it comes to programming, deciding between taking advantage of the ORM or not is a trade-off between immediate convenience and performance.

Make sure you evaluate those trade-offs for your particular situation before blindly deciding in favor or against the ORM.


Accelerate bulk insert using Django's ORM?

I ran some tests on Django 1.10 / Postgresql 9.4 / Pandas 0.19.0 and got the following timings:

  • Insert 3000 rows individually and get ids from populated objects using Django ORM: 3200ms
  • Insert 3000 rows with Pandas and don't get IDs: 774ms
  • Insert 3000 rows with Django manager and don't get IDs: 574ms
  • Insert 3000 rows with to buffer and () and don't get IDs: 118ms
  • Insert 3000 rows with and and get IDs via simple (probably not threadsafe unless holds a lock on the table preventing simultaneous inserts?): 201ms

The performance stats were all obtained on a table already containing 3,000 rows running on OS X (i7 SSD 16GB), average of ten runs using .

I get my inserted primary keys back by assigning an import batch id and sorting by primary key, although I'm not 100% certain primary keys will always be assigned in the order the rows are serialized for the command - would appreciate opinions either way.

Update 2020:

I tested the new functionality in Pandas >= 0.24, which puts all inserts into a single, multi-row insert statement. Surprisingly performance was worse than the single-row version, whether for Pandas versions 0.23, 0.24 or 1.1. Pandas single row inserts were also faster than a multi-row insert statement issued directly to the database. I am using more complex data in a bigger database this time, but and was still around 38% faster than the fastest alternative, which was a single-row , and was occasionally comparable, but often slower still (up to double the time, Django 2.2).

  1. Silver surfer powers
  2. Reconnaissance energy stock price
  3. Cox contour login
  4. Buy kung fu movies
  5. Calvin klein pink robe


"""This is simple snippet to insert multiple data / bulk create in django"""# take example, we have a list of dict datadatas= [{"name": "A", "number: 1, }, {"name": "B","number": 2, }, {"name": "C","number": 3}]# make it as Django objects listdjango_list= [MyModel(**vals) forvalsindatas]# Bulk Create / Insert data to databaseMyModel.objects.bulk_create(django_list)# NOTE: Using this method, the data is inserted in a single query.# but would not calling method `save()`,# it's mean, if you have custom `save()` method this is not good for you# ------------# insert multiple data with insert it one by one (I know this is not good way) This method is iterate the django list and save it to db one by one by calling method `save()`# so if you have custom method `save()` this is will work for you!.# if you have better way to bulk/multiple insert data that also can calling `save()` method, please leave a comment :)

Django framework can be used to create a web application with a database by writing script in and files of the Django app. The data can be inserted into the database tables by using Django Administration Dashboard or by writing a script in the file. Django Administration Dashboard requires a login for an authenticated user to access the tables of the database. Single or multiple records can be inserted into the database tables by writing a script. bulk_create() method is one of the ways to insert multiple records in the database table. How the bulk_create() method is used to insert the multiple data in a Django database table will be shown in this tutorial.


Before practicing the script of this tutorial, you have to complete the following tasks:

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not

Setup a Django app:

Run the following command to create a Django app named bookapp.

$ python3 startapp bookapp

Run the following command to create the user to access the Django database. If you already created one, then you don’t need to run the command.

$ python3 createsuperuser

Add the app name in the INSTALLED_APP part of the file.





Create a folder named templates inside the bookapp folder and set the template’s location of the app in the TEMPLATES part of the file.




                'DIRS': ['/home/fahmida/django_pro/bookapp/templates'],




Create a model for the database table:

Open the file from the bookapp folder and add the following script to define the structure of books tables. Book class is defined to create a table named books with title, author, price, and published_year fields. According to the script, title and author fields will store character data, and price and published_year fields will store the integer data. Here, the title field is defined with the unique attribute. That means that the value of the title field will not accept any duplicate data.

# Import models module

from django.dbimport models

# Define the Book class for the books table

class Book(models.Model):

    title = models.CharField(max_length=100, unique=True)

    author = models.CharField(max_length=100)

    price = models.IntegerField()

    published_year = models.IntegerField()

Run the makemigrations command to create a new migration based on the changes made by the models.

$ python3 makemigrations bookapp

Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the file.

$ python3 migrate

Modify the content of the file with the following content. Here, the Book class of the models is registered using the register() method to display the books tables in the Django administration dashboard.

# Import admin module

from django.contribimport admin

# Import Book model

from .modelsimport Book

# Register Book model

Create a template file named DisplayBookList.html inside the bookapp/templates/ folder with the following script. This script will display all data of books table in tabular form. Other than that, for loop is used in the script to iterate the data passed from the file.





        Django bulk_create() Tutorial



       th { text-align:left; }

       table, th, td { border: 1px solid;}

       h1{ color:Blue;}

       #name{ width:350px;}




<center><h1style="margin-left:20px;">Python Book List</h1></center>




            <th>ID</th><thid="name">Name</th><th>Author</th><th>Publication Year</th><th>Price</th>


       {% for book in object_list %}


           <td>{{}} </td><td>{{book.title}}</td><td>{{}}</td><td>{{book.published_year}}</td><tdstyle="text-align:right">${{book.price}}</td>


          {% endfor %}





Modify the content of the file with the following script. The model and template names are defined in the BulkInsert class. get_queryset() method of the class is defined in the script to return all records of the books table. On the other hand, Book.objects.all() method is used to return all records of the books table. exists() method is used in the script to check the books table is empty or not. If this method returns False then five records will be inserted into the books table using the bulk_create() method.

from django.shortcutsimport render

# Import ListView module

from django.views.genericimport ListView

# Import Book model

from .modelsimport Book

# Define class for inserting multiple data

class BulkInsert(ListView):

    # Define model

    model = Book

    # Define template

    template_name ='DisplayBookList.html'

   # Read all existing records of books table

    queryset = Book.objects.all()

    # Check the books table is empty or not

    if queryset.exists()==False:

       # Insert 5 records in the books table at a time


            Book(title='Python Crash Course, 2nd Edition', author='Eric Matthes', price=15, published_year=2019),

            Book(title='Automate the Boring Stuff with Python, 2nd Edition', author='Al Sweigart', price=30,


            Book(title='Learning Python', author='Mark Lutz', price=15, published_year=2019),

            Book(title='Head First Python', author='Paul Barry', price=45, published_year=2016),

            Book(title='A Byte of Python', author='Swaroop C H', price=15, published_year=2013),



    # Return all records of the books table

    def get_queryset(self):

        # Set the default query set

        return Book.objects.all()

Modify the content of the file with the following script. In the script, the ‘admin/’ path is defined to open the Django Administration Dashboard and the ‘books/’ path is defined to call the BulkInsert.as_view() method that will insert five records to the books table and return the records to the template file.

# Import admin module

from django.contribimport admin

# Import path and include module

from django.urlsimport path

from bookapp import views

urlpatterns =[

    # Define the path for admin


    path('books/', views.BulkInsert.as_view()),


Open the Django Administration Dashboard to check whether the data is inserted properly or not using the bulk_create() function.

The inserted records of the books table will be displayed in the browser after executing the following URL.



Multiple records can be inserted into the Django database table in different ways using the bulk_create(). A simple way of inserting multiple records in the database table using this method was shown in this tutorial to help Django users understand the logic behind the process.


Bulk insert django

Django Bulk Load

Load large batches of Django models into the DB using the Postgres COPY command. This library is a more performant alternative to bulk_create and bulk_update in Django.

Note: Currently, this library only supports Postgres. Other databases may be added in the future.


pip install django-bulk-load


bulk_update_models vs Django's bulk_update vs django-bulk-update


count: 1,000 bulk_update (Django): 0.45329761505126953 bulk_update (django-bulk-update): 0.1036691665649414 bulk_update_models: 0.04524850845336914 count: 10,000 bulk_update (Django): 6.0840747356414795 bulk_update (django-bulk-update): 2.433042049407959 bulk_update_models: 0.10899758338928223 count: 100,000 bulk_update (Django): 647.6648473739624 bulk_update (django-bulk-update): 619.0643970966339 bulk_update_modelsL 0.9625072479248047 count: 1,000,000 bulk_update (Django): Does not complete bulk_update (django-bulk-update): Does not complete bulk_update_models: 14.923949003219604

See this thread for information on Django performance issues.


models=[TestComplexModel(id=i, integer_field=i, string_field=str(i))for i in range(count)] def run_bulk_update_django(): start= time() TestComplexModel.objects.bulk_update(models, fields=["integer_field", "string_field"]) print(time() - start) def run_bulk_update_library(): start= time() TestComplexModel.objects.bulk_update(models, update_fields=["integer_field", "string_field"]) print(time() - start) def run_bulk_update_models(): start= time() bulk_update_models(models) print(time() - start)

bulk_insert_models vs Django's bulk_create



models=[TestComplexModel(integer_field=i, string_field=str(i))for i in range(count)] def run_bulk_create(): start= time() TestComplexModel.objects.bulk_create(models) print(time() - start) def run_bulk_insert_models(): start= time() bulk_insert_models(models) print(time() - start)


Just import and use the functions below. No need to change


INSERT a batch of models. It makes use of the Postgres COPY command to improve speed. If a row already exist, the entire insert will fail. See for descriptions of all parameters.



UPSERT a batch of models. It replicates UPSERTing. By default, it matches existing models using the model , but you can specify matching on other fields with . See for descriptions of all parameters.



UPDATE a batch of models. By default, it matches existing models using the model , but you can specify matching on other fields with . If the model is not found in the database, it is ignored. See for descriptions of all parameters.



INSERTs a new record in the database when a model field has changed in any of , with respect to its latest state, where "latest" is defined by ordering the records for a given primary key by sorting in descending order on the column passed in . Does not INSERT a new record if the latest record has not changed. See for descriptions of all parameters.



Select/Get model dictionaries by filter_field_names. It returns dictionaries, not Django models for performance reasons. This is useful when querying a very large set of models or multiple field IN clauses.



We are not accepting pull requests from anyone outside Cedar employees at this time. All pull requests will be closed.

Use BULK INSERT to load text files into SQL Server Database [HD]


Methods that return new s¶

Django provides a range of refinement methods that modify either the types of results returned by the or the way its SQL query is executed.


Returns a new containing objects that match the given lookup parameters.

The lookup parameters () should be in the format described in Field lookups below. Multiple parameters are joined via in the underlying SQL statement.

If you need to execute more complex queries (for example, queries with statements), you can use .


Returns a new containing objects that do not match the given lookup parameters.

The lookup parameters () should be in the format described in Field lookups below. Multiple parameters are joined via in the underlying SQL statement, and the whole thing is enclosed in a .

This example excludes all entries whose is later than 2005-1-3 AND whose is “Hello”:


In SQL terms, that evaluates to:


This example excludes all entries whose is later than 2005-1-3 OR whose headline is “Hello”:


In SQL terms, that evaluates to:


Note the second example is more restrictive.

If you need to execute more complex queries (for example, queries with statements), you can use .

(*args, **kwargs

Annotates each object in the with the provided list of query expressions. An expression may be a simple value, a reference to a field on the model (or any related models), or an aggregate expression (averages, sums, etc.) that has been computed over the objects that are related to the objects in the .

Each argument to is an annotation that will be added to each object in the that is returned.

The aggregation functions that are provided by Django are described in Aggregation Functions below.

Annotations specified using keyword arguments will use the keyword as the alias for the annotation. Anonymous arguments will have an alias generated for them based upon the name of the aggregate function and the model field that is being aggregated. Only aggregate expressions that reference a single field can be anonymous arguments. Everything else must be a keyword argument.

For example, if you were manipulating a list of blogs, you may want to determine how many entries have been made in each blog:

>>> fromdjango.db.modelsimportCount>>> q=Blog.objects.annotate(Count('entry'))# The name of the first blog>>> q[0].name'Blogasaurus'# The number of entries on the first blog>>> q[0].entry__count42

The model doesn’t define an attribute by itself, but by using a keyword argument to specify the aggregate function, you can control the name of the annotation:

>>> q=Blog.objects.annotate(number_of_entries=Count('entry'))# The number of entries on the first blog, using the name provided>>> q[0].number_of_entries42

For an in-depth discussion of aggregation, see the topic guide on Aggregation.

(*args, **kwargs

Same as , but instead of annotating objects in the , saves the expression for later reuse with other methods. This is useful when the result of the expression itself is not needed but it is used for filtering, ordering, or as a part of a complex expression. Not selecting the unused value removes redundant work from the database which should result in better performance.

For example, if you want to find blogs with more than 5 entries, but are not interested in the exact number of entries, you could do this:

>>> fromdjango.db.modelsimportCount>>> blogs=Blog.objects.alias(entries=Count('entry')).filter(entries__gt=5)

can be used in conjunction with , , , , and . To use aliased expression with other methods (e.g. ), you must promote it to an annotation:


and can take expressions directly, but expression construction and usage often does not happen in the same place (for example, method creates expressions, for later use in views). allows building complex expressions incrementally, possibly spanning multiple methods and modules, refer to the expression parts by their aliases and only use for the final result.


By default, results returned by a are ordered by the ordering tuple given by the option in the model’s . You can override this on a per- basis by using the method.



The result above will be ordered by descending, then by ascending. The negative sign in front of indicates descending order. Ascending order is implied. To order randomly, use , like so:


Note: queries may be expensive and slow, depending on the database backend you’re using.

To order by a field in a different model, use the same syntax as when you are querying across model relations. That is, the name of the field, followed by a double underscore (), followed by the name of the field in the new model, and so on for as many models as you want to join. For example:


If you try to order by a field that is a relation to another model, Django will use the default ordering on the related model, or order by the related model’s primary key if there is no specified. For example, since the model has no default ordering specified:


…is identical to:


If had , then the first queryset would be identical to:


You can also order by query expressions by calling or on the expression:


and have arguments ( and ) that control how null values are sorted.

Be cautious when ordering by fields in related models if you are also using . See the note in for an explanation of how related model ordering can change the expected results.


It is permissible to specify a multi-valued field to order the results by (for example, a field, or the reverse relation of a field).

Consider this case:


Here, there could potentially be multiple ordering data for each ; each with multiple will be returned multiple times into the new that creates. In other words, using on the could return more items than you were working on to begin with - which is probably neither expected nor useful.

Thus, take care when using multi-valued field to order the results. If you can be sure that there will only be one ordering piece of data for each of the items you’re ordering, this approach should not present problems. If not, make sure the results are what you expect.

There’s no way to specify whether ordering should be case sensitive. With respect to case-sensitivity, Django will order results however your database backend normally orders them.

You can order by a field converted to lowercase with which will achieve case-consistent ordering:


If you don’t want any ordering to be applied to a query, not even the default ordering, call with no parameters.

You can tell if a query is ordered or not by checking the attribute, which will be if the has been ordered in any way.

Each call will clear any previous ordering. For example, this query will be ordered by and not :



Ordering is not a free operation. Each field you add to the ordering incurs a cost to your database. Each foreign key you add will implicitly include all of its default orderings as well.

If a query doesn’t have an ordering specified, results are returned from the database in an unspecified order. A particular ordering is guaranteed only when ordering by a set of fields that uniquely identify each object in the results. For example, if a field isn’t unique, ordering by it won’t guarantee objects with the same name always appear in the same order.


Use the method to reverse the order in which a queryset’s elements are returned. Calling a second time restores the ordering back to the normal direction.

To retrieve the “last” five items in a queryset, you could do this:


Note that this is not quite the same as slicing from the end of a sequence in Python. The above example will return the last item first, then the penultimate item and so on. If we had a Python sequence and looked at , we would see the fifth-last item first. Django doesn’t support that mode of access (slicing from the end), because it’s not possible to do it efficiently in SQL.

Also, note that should generally only be called on a which has a defined ordering (e.g., when querying against a model which defines a default ordering, or when using ). If no such ordering is defined for a given , calling on it has no real effect (the ordering was undefined prior to calling , and will remain undefined afterward).


Returns a new that uses in its SQL query. This eliminates duplicate rows from the query results.

By default, a will not eliminate duplicate rows. In practice, this is rarely a problem, because simple queries such as don’t introduce the possibility of duplicate result rows. However, if your query spans multiple tables, it’s possible to get duplicate results when a is evaluated. That’s when you’d use .


Any fields used in an call are included in the SQL columns. This can sometimes lead to unexpected results when used in conjunction with . If you order by fields from a related model, those fields will be added to the selected columns and they may make otherwise duplicate rows appear to be distinct. Since the extra columns don’t appear in the returned results (they are only there to support ordering), it sometimes looks like non-distinct results are being returned.

Similarly, if you use a query to restrict the columns selected, the columns used in any (or default model ordering) will still be involved and may affect uniqueness of the results.

The moral here is that if you are using be careful about ordering by related models. Similarly, when using and together, be careful when ordering by fields not in the call.

On PostgreSQL only, you can pass positional arguments () in order to specify the names of fields to which the should apply. This translates to a SQL query. Here’s the difference. For a normal call, the database compares each field in each row when determining which rows are distinct. For a call with specified field names, the database will only compare the specified field names.


When you specify field names, you must provide an in the , and the fields in must start with the fields in , in the same order.

For example, gives you the first row for each value in column . If you don’t specify an order, you’ll get some arbitrary row.

Examples (those after the first will only work on PostgreSQL):

>>> Author.objects.distinct()[...]>>> Entry.objects.order_by('pub_date').distinct('pub_date')[...]>>> Entry.objects.order_by('blog').distinct('blog')[...]>>> Entry.objects.order_by('author','pub_date').distinct('author','pub_date')[...]>>> Entry.objects.order_by('blog__name','mod_date').distinct('blog__name','mod_date')[...]>>> Entry.objects.order_by('author','pub_date').distinct('author')[...]


Keep in mind that uses any default related model ordering that has been defined. You might have to explicitly order by the relation or referenced field to make sure the expressions match those at the beginning of the clause. For example, if the model defined an by :


…wouldn’t work because the query would be ordered by thus mismatching the expression. You’d have to explicitly order by the relation field ( in this case) or the referenced one () to make sure both expressions match.

(*fields, **expressions

Returns a that returns dictionaries, rather than model instances, when used as an iterable.

Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

This example compares the dictionaries of with the normal model objects:

# This list contains a Blog object.>>>Blog.objects.filter(name__startswith='Beatles')<QuerySet[<Blog:BeatlesBlog>]># This list contains a dictionary.>>>Blog.objects.filter(name__startswith='Beatles').values()<QuerySet[{'id':1,'name':'Beatles Blog','tagline':'All the latest Beatles news.'}]>

The method takes optional positional arguments, , which specify field names to which the should be limited. If you specify the fields, each dictionary will contain only the field keys/values for the fields you specify. If you don’t specify the fields, each dictionary will contain a key and value for every field in the database table.


>>> Blog.objects.values()<QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>>>> Blog.objects.values('id','name')<QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>

The method also takes optional keyword arguments, , which are passed through to :

>>> fromdjango.db.models.functionsimportLower>>> Blog.objects.values(lower_name=Lower('name'))<QuerySet [{'lower_name': 'beatles blog'}]>

You can use built-in and custom lookups in ordering. For example:

>>> fromdjango.db.modelsimportCharField>>> fromdjango.db.models.functionsimportLower>>> CharField.register_lookup(Lower)>>> Blog.objects.values('name__lower')<QuerySet [{'name__lower': 'beatles blog'}]>

An aggregate within a clause is applied before other arguments within the same clause. If you need to group by another value, add it to an earlier clause instead. For example:

>>> fromdjango.db.modelsimportCount>>> Blog.objects.values('entry__authors',entries=Count('entry'))<QuerySet [{'entry__authors': 1, 'entries': 20}, {'entry__authors': 1, 'entries': 13}]>>>> Blog.objects.values('entry__authors').annotate(entries=Count('entry'))<QuerySet [{'entry__authors': 1, 'entries': 33}]>

A few subtleties that are worth mentioning:

  • If you have a field called that is a , the default call will return a dictionary key called , since this is the name of the hidden model attribute that stores the actual value (the attribute refers to the related model). When you are calling and passing in field names, you can pass in either or and you will get back the same thing (the dictionary key will match the field name you passed in).

    For example:

    >>> Entry.objects.values()<QuerySet [{'blog_id': 1, 'headline': 'First Entry', ...}, ...]>>>> Entry.objects.values('blog')<QuerySet [{'blog': 1}, ...]>>>> Entry.objects.values('blog_id')<QuerySet [{'blog_id': 1}, ...]>
  • When using together with , be aware that ordering can affect the results. See the note in for details.

  • If you use a clause after an call, any fields defined by a argument in the must be explicitly included in the call. Any call made after a call will have its extra selected fields ignored.

  • Calling and after doesn’t make sense, so doing so will raise a .

  • Combining transforms and aggregates requires the use of two calls, either explicitly or as keyword arguments to . As above, if the transform has been registered on the relevant field type the first can be omitted, thus the following examples are equivalent:

    >>> fromdjango.db.modelsimportCharField,Count>>> fromdjango.db.models.functionsimportLower>>> CharField.register_lookup(Lower)>>> Blog.objects.values('entry__authors__name__lower').annotate(entries=Count('entry'))<QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>>>> Blog.objects.values(... entry__authors__name__lower=Lower('entry__authors__name')... ).annotate(entries=Count('entry'))<QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>>>> Blog.objects.annotate(... entry__authors__name__lower=Lower('entry__authors__name')... ).values('entry__authors__name__lower').annotate(entries=Count('entry'))<QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>

It is useful when you know you’re only going to need values from a small number of the available fields and you won’t need the functionality of a model instance object. It’s more efficient to select only the fields you need to use.

Finally, note that you can call , , etc. after the call, that means that these two calls are identical:


The people who made Django prefer to put all the SQL-affecting methods first, followed (optionally) by any output-affecting methods (such as ), but it doesn’t really matter. This is your chance to really flaunt your individualism.

You can also refer to fields on related models with reverse relations through , and attributes:

>>> Blog.objects.values('name','entry__headline')<QuerySet [{'name': 'My blog', 'entry__headline': 'An entry'}, {'name': 'My blog', 'entry__headline': 'Another entry'}, ...]>


Because attributes and reverse relations can have multiple related rows, including these can have a multiplier effect on the size of your result set. This will be especially pronounced if you include multiple such fields in your query, in which case all possible combinations will be returned.

Boolean values for on SQLite

Due to the way the SQL function is implemented on SQLite, will return and instead of and for key transforms.

(*fields, flat=False, named=False

This is similar to except that instead of returning dictionaries, it returns tuples when iterated over. Each tuple contains the value from the respective field or expression passed into the call — so the first item is the first field, etc. For example:

>>> Entry.objects.values_list('id','headline')<QuerySet [(1, 'First entry'), ...]>>>> fromdjango.db.models.functionsimportLower>>> Entry.objects.values_list('id',Lower('headline'))<QuerySet [(1, 'first entry'), ...]>

If you only pass in a single field, you can also pass in the parameter. If , this will mean the returned results are single values, rather than one-tuples. An example should make the difference clearer:

>>> Entry.objects.values_list('id').order_by('id')<QuerySet[(1,), (2,), (3,), ...]>>>> Entry.objects.values_list('id',flat=True).order_by('id')<QuerySet [1, 2, 3, ...]>

It is an error to pass in when there is more than one field.

You can pass to get results as a :

>>> Entry.objects.values_list('id','headline',named=True)<QuerySet [Row(id=1, headline='First entry'), ...]>

Using a named tuple may make use of the results more readable, at the expense of a small performance penalty for transforming the results into a named tuple.

If you don’t pass any values to , it will return all the fields in the model, in the order they were declared.

A common need is to get a specific field value of a certain model instance. To achieve that, use followed by a call:

>>> Entry.objects.values_list('headline',flat=True).get(pk=1)'First entry'

and are both intended as optimizations for a specific use case: retrieving a subset of data without the overhead of creating a model instance. This metaphor falls apart when dealing with many-to-many and other multivalued relations (such as the one-to-many relation of a reverse foreign key) because the “one row, one object” assumption doesn’t hold.

For example, notice the behavior when querying across a :

>>> Author.objects.values_list('name','entry__headline')<QuerySet [('Noam Chomsky', 'Impressions of Gaza'), ('George Orwell', 'Why Socialists Do Not Believe in Fun'), ('George Orwell', 'In Defence of English Cooking'), ('Don Quixote', None)]>

Authors with multiple entries appear multiple times and authors without any entries have for the entry headline.

Similarly, when querying a reverse foreign key, appears for entries not having any author:

>>> Entry.objects.values_list('authors')<QuerySet [('Noam Chomsky',), ('George Orwell',), (None,)]>

Boolean values for on SQLite

Due to the way the SQL function is implemented on SQLite, will return and instead of and for key transforms.

(field, kind, order='ASC'

Returns a that evaluates to a list of objects representing all available dates of a particular kind within the contents of the .

should be the name of a of your model. should be either , , , or . Each object in the result list is “truncated” to the given .

  • returns a list of all distinct year values for the field.
  • returns a list of all distinct year/month values for the field.
  • returns a list of all distinct year/week values for the field. All dates will be a Monday.
  • returns a list of all distinct year/month/day values for the field.

, which defaults to , should be either or . This specifies how to order the results.


>>> Entry.objects.dates('pub_date','year')[, 1, 1)]>>> Entry.objects.dates('pub_date','month')[, 2, 1),, 3, 1)]>>> Entry.objects.dates('pub_date','week')[, 2, 14),, 3, 14)]>>> Entry.objects.dates('pub_date','day')[, 2, 20),, 3, 20)]>>> Entry.objects.dates('pub_date','day',order='DESC')[, 3, 20),, 2, 20)]>>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date','day')[, 3, 20)]

(field_name, kind, order='ASC', tzinfo=None, is_dst=None

Returns a that evaluates to a list of objects representing all available dates of a particular kind within the contents of the .

should be the name of a of your model.

should be either , , , , , , or . Each object in the result list is “truncated” to the given .

, which defaults to , should be either or . This specifies how to order the results.

defines the time zone to which datetimes are converted prior to truncation. Indeed, a given datetime has different representations depending on the time zone in use. This parameter must be a object. If it’s , Django uses the current time zone. It has no effect when is .

indicates whether or not should interpret nonexistent and ambiguous datetimes in daylight saving time. By default (when ), raises an exception for such datetimes.

New in Django 3.1:

The parameter was added.


This function performs time zone conversions directly in the database. As a consequence, your database must be able to interpret the value of . This translates into the following requirements:


Calling will create a queryset that never returns any objects and no query will be executed when accessing the results. A queryset is an instance of .


>>> Entry.objects.none()<QuerySet []>>>> fromdjango.db.models.queryimportEmptyQuerySet>>> isinstance(Entry.objects.none(),EmptyQuerySet)True


Returns a copy of the current (or subclass). This can be useful in situations where you might want to pass in either a model manager or a and do further filtering on the result. After calling on either object, you’ll definitely have a to work with.

When a is evaluated, it typically caches its results. If the data in the database might have changed since a was evaluated, you can get updated results for the same query by calling on a previously evaluated .

(*other_qs, all=False

Uses SQL’s operator to combine the results of two or more s. For example:

>>> qs1.union(qs2,qs3)

The operator selects only distinct values by default. To allow duplicate values, use the argument.

, , and return model instances of the type of the first even if the arguments are s of other models. Passing different models works as long as the list is the same in all s (at least the types, the names don’t matter as long as the types are in the same order). In such cases, you must use the column names from the first in methods applied to the resulting . For example:

>>> qs1=Author.objects.values_list('name')>>> qs2=Entry.objects.values_list('headline')>>> qs1.union(qs2).order_by('name')

In addition, only , , , , and specifying columns (i.e. slicing, , , , and /) are allowed on the resulting . Further, databases place restrictions on what operations are allowed in the combined queries. For example, most databases don’t allow or in the combined queries.


Uses SQL’s operator to return the shared elements of two or more s. For example:

>>> qs1.intersection(qs2,qs3)

See for some restrictions.


Uses SQL’s operator to keep only elements present in the but not in some other s. For example:

>>> qs1.difference(qs2,qs3)

See for some restrictions.


Returns a that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query. This is a performance booster which results in a single more complex query but means later use of foreign-key relationships won’t require database queries.

The following examples illustrate the difference between plain lookups and lookups. Here’s standard lookup:

# Hits the database.e=Entry.objects.get(id=5)# Hits the database again to get the related Blog

And here’s lookup:

# Hits the database.e=Entry.objects.select_related('blog').get(id=5)# Doesn't hit the database, because has been prepopulated# in the previous

You can use with any queryset of objects:

fromdjango.utilsimporttimezone# Find all the blogs with entries scheduled to be published in the future.blogs=set()foreinEntry.objects.filter('blog'):# Without select_related(), this would make a database query for each# loop iteration in order to fetch the related blog for each entry.blogs.add(

The order of and chaining isn’t important. These querysets are equivalent:


You can follow foreign keys in a similar way to querying them. If you have the following models:

fromdjango.dbimportmodelsclassCity(models.Model):# ...passclassPerson(models.Model):# ...hometown=models.ForeignKey(City,on_delete=models.SET_NULL,blank=True,null=True,)classBook(models.Model):#,on_delete=models.CASCADE)

… then a call to will cache the related and the related :

# Hits the database with joins to the author and hometown tables.b=Book.objects.select_related('author__hometown').get(id=4) Doesn't hit the database.c=p.hometown# Doesn't hit the database.# Without select_related()...b=Book.objects.get(id=4)# Hits the Hits the database.c=p.hometown# Hits the database.

You can refer to any or relation in the list of fields passed to .

You can also refer to the reverse direction of a in the list of fields passed to — that is, you can traverse a back to the object on which the field is defined. Instead of specifying the field name, use the for the field on the related object.

There may be some situations where you wish to call with a lot of related objects, or where you don’t know all of the relations. In these cases it is possible to call with no arguments. This will follow all non-null foreign keys it can find - nullable foreign keys must be specified. This is not recommended in most cases as it is likely to make the underlying query more complex, and return more data, than is actually needed.

If you need to clear the list of related fields added by past calls of on a , you can pass as a parameter:

>>> without_relations=queryset.select_related(None)

Chaining calls works in a similar way to other methods - that is that is equivalent to .


Returns a that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to , in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

works by creating an SQL join and including the fields of the related object in the statement. For this reason, gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, is limited to single-valued relationships - foreign key and one-to-one.

, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using , in addition to the foreign key and one-to-one relationships that are supported by . It also supports prefetching of and , however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a is only supported if the query is restricted to one .

For example, suppose you have these models:

fromdjango.dbimportmodelsclassTopping(models.Model):name=models.CharField(max_length=30)classPizza(models.Model):name=models.CharField(max_length=50)toppings=models.ManyToManyField(Topping)def__str__(self):return"%s (%s)"%(,", ".join(topping.namefortoppinginself.toppings.all()),)

and run:

>>> Pizza.objects.all()["Hawaiian (ham, pineapple)", "Seafood (prawns, smoked salmon)"...

The problem with this is that every time asks for it has to query the database, so will run a query on the Toppings table for every item in the Pizza .

We can reduce to just two queries using :

>>> Pizza.objects.all().prefetch_related('toppings')

This implies a for each ; now each time is called, instead of having to go to the database for the items, it will find them in a prefetched cache that was populated in a single query.

That is, all the relevant toppings will have been fetched in a single query, and used to make that have a pre-filled cache of the relevant results; these are then used in the calls.

The additional queries in are executed after the has begun to be evaluated and the primary query has been executed.

If you have an iterable of model instances, you can prefetch related attributes on those instances using the function.

Note that the result cache of the primary and all specified related objects will then be fully loaded into memory. This changes the typical behavior of , which normally try to avoid loading all objects into memory before they are needed, even after a query has been executed in the database.


Remember that, as always with , any subsequent chained methods which imply a different database query will ignore previously cached results, and retrieve data using a fresh database query. So, if you write the following:

>>> pizzas=Pizza.objects.prefetch_related('toppings')>>> [list(pizza.toppings.filter(spicy=True))forpizzainpizzas]

…then the fact that has been prefetched will not help you. The implied , but is a new and different query. The prefetched cache can’t help here; in fact it hurts performance, since you have done a database query that you haven’t used. So use this feature with caution!

Also, if you call the database-altering methods , , or , on , any prefetched cache for the relation will be cleared.

You can also use the normal join syntax to do related fields of related fields. Suppose we have an additional model to the example above:


The following are all legal:

>>> Restaurant.objects.prefetch_related('pizzas__toppings')

This will prefetch all pizzas belonging to restaurants, and all toppings belonging to those pizzas. This will result in a total of 3 database queries - one for the restaurants, one for the pizzas, and one for the toppings.

>>> Restaurant.objects.prefetch_related('best_pizza__toppings')

This will fetch the best pizza and all the toppings for the best pizza for each restaurant. This will be done in 3 database queries - one for the restaurants, one for the ‘best pizzas’, and one for the toppings.

The relationship could also be fetched using to reduce the query count to 2:

>>> Restaurant.objects.select_related('best_pizza').prefetch_related('best_pizza__toppings')

Since the prefetch is executed after the main query (which includes the joins needed by ), it is able to detect that the objects have already been fetched, and it will skip fetching them again.

Chaining calls will accumulate the lookups that are prefetched. To clear any behavior, pass as a parameter:

>>> non_prefetched=qs.prefetch_related(None)

One difference to note when using is that objects created by a query can be shared between the different objects that they are related to i.e. a single Python model instance can appear at more than one point in the tree of objects that are returned. This will normally happen with foreign key relationships. Typically this behavior will not be a problem, and will in fact save both memory and CPU time.

While supports prefetching relationships, the number of queries will depend on the data. Since a can reference data in multiple tables, one query per table referenced is needed, rather than one query for all the items. There could be additional queries on the table if the relevant rows have not already been fetched.

in most cases will be implemented using an SQL query that uses the ‘IN’ operator. This means that for a large a large ‘IN’ clause could be generated, which, depending on the database, might have performance problems of its own when it comes to parsing or executing the SQL query. Always profile for your use case!

Note that if you use to run the query, calls will be ignored since these two optimizations do not make sense together.

You can use the object to further control the prefetch operation.

In its simplest form is equivalent to the traditional string based lookups:

>>> fromdjango.db.modelsimportPrefetch>>> Restaurant.objects.prefetch_related(Prefetch('pizzas__toppings'))

You can provide a custom queryset with the optional argument. This can be used to change the default ordering of the queryset:

>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas__toppings',queryset=Toppings.objects.order_by('name')))

Or to call when applicable to reduce the number of queries even further:

>>> Pizza.objects.prefetch_related(... Prefetch('restaurants',queryset=Restaurant.objects.select_related('best_pizza')))

You can also assign the prefetched result to a custom attribute with the optional argument. The result will be stored directly in a list.

This allows prefetching the same relation multiple times with a different ; for instance:

>>> vegetarian_pizzas=Pizza.objects.filter(vegetarian=True)>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas',to_attr='menu'),... Prefetch('pizzas',queryset=vegetarian_pizzas,to_attr='vegetarian_menu'))

Lookups created with custom can still be traversed as usual by other lookups:

>>> vegetarian_pizzas=Pizza.objects.filter(vegetarian=True)>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas',queryset=vegetarian_pizzas,to_attr='vegetarian_menu'),... 'vegetarian_menu__toppings')

Using is recommended when filtering down the prefetch result as it is less ambiguous than storing a filtered result in the related manager’s cache:

>>> queryset=Pizza.objects.filter(vegetarian=True)>>>>>> # Recommended:>>> restaurants=Restaurant.objects.prefetch_related(... Prefetch('pizzas',queryset=queryset,to_attr='vegetarian_pizzas'))>>> vegetarian_pizzas=restaurants[0].vegetarian_pizzas>>>>>> # Not recommended:>>> restaurants=Restaurant.objects.prefetch_related(... Prefetch('pizzas',queryset=queryset))>>> vegetarian_pizzas=restaurants[0].pizzas.all()

Custom prefetching also works with single related relations like forward or . Generally you’ll want to use for these relations, but there are a number of cases where prefetching with a custom is useful:

  • You want to use a that performs further prefetching on related models.

  • You want to prefetch only a subset of the related objects.

  • You want to use performance optimization techniques like :

    >>> queryset=Pizza.objects.only('name')>>>>>> restaurants=Restaurant.objects.prefetch_related(... Prefetch('best_pizza',queryset=queryset))

When using multiple databases, will respect your choice of database. If the inner query does not specify a database, it will use the database selected by the outer query. All of the following are valid:

>>> # Both inner and outer queries will use the 'replica' database>>> Restaurant.objects.prefetch_related('pizzas__toppings').using('replica')>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas__toppings'),... ).using('replica')>>>>>> # Inner will use the 'replica' database; outer will use 'default' database>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas__toppings',queryset=Toppings.objects.using('replica')),... )>>>>>> # Inner will use 'replica' database; outer will use 'cold-storage' database>>> Restaurant.objects.prefetch_related(... Prefetch('pizzas__toppings',queryset=Toppings.objects.using('replica')),... ).using('cold-storage')


The ordering of lookups matters.

Take the following examples:

>>> prefetch_related('pizzas__toppings','pizzas')

This works even though it’s unordered because already contains all the needed information, therefore the second argument is actually redundant.

>>> prefetch_related('pizzas__toppings',Prefetch('pizzas',queryset=Pizza.objects.all()))

This will raise a because of the attempt to redefine the queryset of a previously seen lookup. Note that an implicit queryset was created to traverse as part of the lookup.

>>> prefetch_related('pizza_list__toppings',Prefetch('pizzas',to_attr='pizza_list'))

This will trigger an because doesn’t exist yet when is being processed.

This consideration is not limited to the use of objects. Some advanced techniques may require that the lookups be performed in a specific order to avoid creating extra queries; therefore it’s recommended to always carefully order arguments.

(select=None, where=None, params=None, tables=None, order_by=None, select_params=None

Sometimes, the Django query syntax by itself can’t easily express a complex clause. For these edge cases, Django provides the modifier — a hook for injecting specific clauses into the SQL generated by a .

Use this method as a last resort

This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods. If you do need to use it, please file a ticket using the QuerySet.extra keyword with your use case (please check the list of existing tickets first) so that we can enhance the QuerySet API to allow removing . We are no longer improving or fixing bugs for this method.

For example, this use of :

>>> qs.extra(... select={'val':"select col from sometable where othercol = %s"},... select_params=(someparam,),... )

is equivalent to:

>>> qs.annotate(val=RawSQL("select col from sometable where othercol = %s",(someparam,)))

The main benefit of using is that you can set if needed. The main downside is that if you refer to some table alias of the queryset in the raw SQL, then it is possible that Django might change that alias (for example, when the queryset is used as a subquery in yet another query).


You should be very careful whenever you use . Every time you use it, you should escape any parameters that the user can control by using in order to protect against SQL injection attacks.

You also must not quote placeholders in the SQL string. This example is vulnerable to SQL injection because of the quotes around :


You can read more about how Django’s SQL injection protection works.

By definition, these extra lookups may not be portable to different database engines (because you’re explicitly writing SQL code) and violate the DRY principle, so you should avoid them if possible.

Specify one or more of , , or . None of the arguments is required, but you should use at least one of them.

  • The argument lets you put extra fields in the clause. It should be a dictionary mapping attribute names to SQL clauses to use to calculate that attribute.


    Entry.objects.extra(select={'is_recent':"pub_date > '2006-01-01'"})

    As a result, each object will have an extra attribute, , a boolean representing whether the entry’s is greater than Jan. 1, 2006.

    Django inserts the given SQL snippet directly into the statement, so the resulting SQL of the above example would be something like:


    The next example is more advanced; it does a subquery to give each resulting object an attribute, an integer count of associated objects:

    Blog.objects.extra(select={'entry_count':'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id ='},)

    In this particular case, we’re exploiting the fact that the query will already contain the table in its clause.

    The resulting SQL of the above example would be:


    Note that the parentheses required by most database engines around subqueries are not required in Django’s clauses. Also note that some database backends, such as some MySQL versions, don’t support subqueries.

    In some rare cases, you might wish to pass parameters to the SQL fragments in . For this purpose, use the parameter.

    This will work, for example:


    If you need to use a literal inside your select string, use the sequence .

  • /

    You can define explicit SQL clauses — perhaps to perform non-explicit joins — by using . You can manually add tables to the SQL clause by using .

    and both take a list of strings. All parameters are “AND”ed to any other search criteria.


    Entry.objects.extra(where=["foo='a' OR bar = 'a'","baz = 'a'"])

    …translates (roughly) into the following SQL:


    Be careful when using the parameter if you’re specifying tables that are already used in the query. When you add extra tables via the parameter, Django assumes you want that table included an extra time, if it is already included. That creates a problem, since the table name will then be given an alias. If a table appears multiple times in an SQL statement, the second and subsequent occurrences must use aliases so the database can tell them apart. If you’re referring to the extra table you added in the extra parameter this is going to cause errors.

    Normally you’ll only be adding extra tables that don’t already appear in the query. However, if the case outlined above does occur, there are a few solutions. First, see if you can get by without including the extra table and use the one already in the query. If that isn’t possible, put your call at the front of the queryset construction so that your table is the first use of that table. Finally, if all else fails, look at the query produced and rewrite your addition to use the alias given to your extra table. The alias will be the same each time you construct the queryset in the same way, so you can rely upon the alias name to not change.

  • If you need to order the resulting queryset using some of the new fields or tables you have included via use the parameter to and pass in a sequence of strings. These strings should either be model fields (as in the normal method on querysets), of the form or an alias for a column that you specified in the parameter to .

    For example:

    q=Entry.objects.extra(select={'is_recent':"pub_date > '2006-01-01'"})q=q.extra(order_by=['-is_recent'])

    This would sort all the items for which is true to the front of the result set ( sorts before in a descending ordering).

    This shows, by the way, that you can make multiple calls to and it will behave as you expect (adding new constraints each time).

  • The parameter described above may use standard Python database string placeholders — to indicate parameters the database engine should automatically quote. The argument is a list of any extra parameters to be substituted.



    Always use instead of embedding values directly into because will ensure values are quoted correctly according to your particular backend. For example, quotes will be escaped correctly.






If you are performing queries on MySQL, note that MySQL’s silent type coercion may cause unexpected results when mixing types. If you query on a string type column, but with an integer value, MySQL will coerce the types of all values in the table to an integer before performing the comparison. For example, if your table contains the values , and you query for , both rows will match. To prevent this, perform the correct typecasting before using the value in a query.


In some complex data-modeling situations, your models might contain a lot of fields, some of which could contain a lot of data (for example, text fields), or require expensive processing to convert them to Python objects. If you are using the results of a queryset in some situation where you don’t know if you need those particular fields when you initially fetch the data, you can tell Django not to retrieve them from the database.

This is done by passing the names of the fields to not load to :


A queryset that has deferred fields will still return model instances. Each deferred field will be retrieved from the database if you access that field (one at a time, not all the deferred fields at once).

You can make multiple calls to . Each call adds new fields to the deferred set:

# Defers both the body and headline fields.Entry.objects.defer("body").filter(rating=5).defer("headline")

The order in which fields are added to the deferred set does not matter. Calling with a field name that has already been deferred is harmless (the field will still be deferred).

You can defer loading of fields in related models (if the related models are loading via ) by using the standard double-underscore notation to separate related fields:


If you want to clear the set of deferred fields, pass as a parameter to :

# Load all fields immediately.my_queryset.defer(None)

Some fields in a model won’t be deferred, even if you ask for them. You can never defer the loading of the primary key. If you are using to retrieve related models, you shouldn’t defer the loading of the field that connects from the primary model to the related one, doing so will result in an error.


The method (and its cousin, , below) are only for advanced use-cases. They provide an optimization for when you have analyzed your queries closely and understand exactly what information you need and have measured that the difference between returning the fields you need and the full set of fields for the model will be significant.

Even if you think you are in the advanced use-case situation, only use defer() when you cannot, at queryset load time, determine if you will need the extra fields or not. If you are frequently loading and using a particular subset of your data, the best choice you can make is to normalize your models and put the non-loaded data into a separate model (and database table). If the columns must stay in the one table for some reason, create a model with (see the


Similar news:

“django bulk create” Code Answer’s

Python answers related to “django bulk create”

Python queries related to “django bulk create”

Browse Python Answers by Framework

More “Kinda” Related Python Answers View All Python Answers »

  • django version check
  • change django administration title
  • django template tag to display current year
  • django EMAIL_BACKEND console
  • django import Q
  • q is not defined pylance django
  • django admin create superuser
  • truncate templat tag django
  • check django object exists
  • django no such table
  • installing django
  • import validation error in django
  • django return httpresponse
  • django return html response
  • django make migrations
  • django reset database
  • django flush
  • import user in django
  • crispy forms
  • postgres django
  • django postgres
  • how to use postgresql with django
  • django flush database
  • create new django app
  • django create app command
  • django humanize
  • starting server in django
  • media url django
  • how to override save method in django
  • raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: home.html
  • django user group check
  • create tenant django
  • run django app locally
  • allauth
  • include all fields
  • bootstrap Navbar active in django
  • how to generate requirements.txt django
  • django how to set a navbar active
  • database default code in settings django
  • importying listviewin django
  • django form password field
  • django sum get 0 if none
  • django postgres user permissions
  • create or update django models
  • django create empty migration
  • require http method django view
  • django model field not required
  • django load model by name
  • django timezone india
  • django forms set class
  • django debug toolbar
  • django-tool-bar
  • django is null
  • ckeditor django
  • how to migrate from sqlite to postgresql django
  • django import model from another app
  • django desc order
  • django create app
  • django admin register mdoel
  • how to multiply in django template
  • csrf token exempt django
  • disable csrf for one url django
  • message in django
  • django login redirect
  • import forms
  • leduong django api
  • Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
  • django read mesage
  • django message framework
  • django messages
  • messages django
  • sql alchemy engine all tables
  • how to know connected user in django
  • no such table: django_session
  • urlpatterns = [ path('SignUp/', views.SignupPage, name='user_data')\
  • django include
  • favicon django
  • connect to mysql sqlalchemy
  • django-admin command not found
  • django integer field example
  • django jinja subset string
  • django return only part of string
  • django httpresponseredirect
  • forloop counter django
  • for loop django template count
  • django loop index
  • django model specify table name
  • redirect django
  • django postgres connection
  • how to send json in django response
  • django logout
  • delete model object django
  • django delete object
  • django log sql queries
  • permanent redirect django
  • decimal field django
  • django reverse
  • field.choices django
  • django raise 404
  • access the value in settings django
  • autoslugfield django 3
  • add year to id django
  • backup django db from one database to another
  • yesno django
  • get most repeated instance in a queryset django
  • add search field to django admin
  • filter with different operator in django
  • django model query add annotation field to show duplicate count
  • django get part of queryset
  • mongodb python get all documents
  • django rest framework datatables does not paginate
  • django and operator
  • django text area limit characters
  • django python install
  • django-admin startproject
  • order by listview django
  • django admin slug auto populate
  • url in form action django
  • django making a custom 403 page
  • number of database queries django
  • django admin prefetch_related
  • django dumpdata
  • how to count post by category django
  • django m2m .add
  • object.image.url email template django
  • how to make booking website using django step by step
  • createview
  • createview django
  • start new app in django
  • django create model from dictionary
  • django update model
  • django unique_together
  • my django template doesnt want to load the static file
  • mongodb group by having
  • django model verbose name
  • how to add an active class to current element in navbar in django
  • how to set required drf serialzier
  • django foreign key field on delete do nothing
  • django genericforeignkey null
  • and condition with or in django
  • _set in django
  • django drop database postgres
  • import models
  • django populate choice field from database
  • django 3 add template folder
  • using regex validators in django models
  • install models python
  • install crossheaders in django
  • django models distinct
  • django queryset get all distinct
  • django rest framework
  • django rest
  • pip install django rest framework
  • delete database entry using name django
  • count gabarit django
  • how to get last values or data in django orm
  • django.db.utils.OperationalError: no such table:
  • make new app folder in django templates dir
  • django models add foreign key
  • how to logout in django
  • how to run the server in django
  • hide particular attribute in django admin
  • django override delete
  • select realted for foreign key table in django
  • how to get only first record in django
  • django.core.exceptions.ImproperlyConfigured
  • how to create migrations in django
  • django get model class from queryset
  • django print settings
  • slugify django
  • slug django
  • django unique slug
  • if django
  • django template tags if statmenet
  • django setup allowed hosts
  • Change date format on django templates
  • date format django template filter
  • pip update django
  • django group by date from datetime field
  • django templateview
  • install django using pip
  • how to check if given primary key exists in django model
  • create django model field based on another field
  • listview django
  • django get current date
  • make column nullable django
  • django datetimefield default
  • q django
  • fake migration
  • django new static files directory
  • add static file in django
  • registering static files in jango
  • static dirs django
  • change default port django
  • how to save bulk create in django
  • sum values in django models
  • import authenticate
  • django authenticate
  • django template for range
  • django clear db
  • on_delete options django
  • django try catch exception
  • add background image in django uploaded file
  • how to delete migrations in django
  • user group template tag django
  • how store list in django session
  • python django shell command
  • managin media django
  • template does not exist django
  • how to pass data between views django
  • django sign up
  • get current site django
  • localhost postgres settings django
  • django csrf form
  • how to redirect to previous page in django
  • create django user command line
  • no such table: django_session admin
  • simple jwt django
  • django rest framework simple jwt
  • rest_framework_simplejwt
  • django deleteview class
  • install django rest_framework
  • django filter in list
  • close django server
  • django regexvalidator example
  • zip django template
  • set the context data in django listview
  • django dynamic pages
  • runpython django migration
  • django runpython
  • run django server
  • how to start a new django project
  • elif in django template
  • how to make django model field case insensitive
  • django empty queryset
  • get list of users django
  • django logout user
  • what is cleaned data in django
  • import views
  • how to count range in django template
  • get a list of ids from queryset django
  • django admin customization
  • get user ip address django
  • django user fields
  • how to get a hyperlink in django
  • what is values_list in django orm
  • django dataload
  • django add custom commands to
  • runserver
  • django runserver
  • django datefield options
  • django admin password reset
  • urlpatterns += static(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT})
  • change admin password djano
  • forgot django admin password
  • check date on template django
  • import status in django rest framework
  • image delete in django from the folder
  • how to run django requirement.txt
  • how to insert a placeholder text in django modelform
  • add field placeholder layout crispy modelform
  • django admin no such table user
  • get ip address in django
  • django url static
  • django url patterns static
  • django ckeditor not working
  • django cleanup
  • query with condition django
  • latest version of django
  • pip install django
  • Your models have changes that are not yet reflected in a migration, and so won't be applied. Run ' makemigrations' to make new migrations, and then re-run ' migrate' to apply them.
  • django rest framework viewset
  • django q filter
  • django no such column
  • how do i check if a django queryset is empty
  • how to require login for Django function views
  • how to get the current url path in django template
  • Static Assets in Django
  • primary key django model
  • django-cors-headers
  • Access-Control-Allow-Origin django
  • django order by
  • django model queries orber by
  • for loop in django
  • passing user instance django form submission
  • email field in django
  • no module named social_django
  • redirect a post request django
  • django admin link
  • request.body django
  • django objects.create()
  • environment variables django
  • django createmany
  • create models in django
  • update django
  • django link home page
  • django radio button
  • how to use static files in django
  • AttributeError: This QueryDict instance is immutable django
  • how to check if django is installed( in python shell)
  • django csfr token
  • Django Rendering Forms Manually and using csfr token
  • django request user
  • django 3 check if user is logged in
  • file manage py line 17 from exc django
  • django url tag
  • django admin action
  • get value from post request django
  • adding content search bar in blog django
  • django __str__ self multiple
  • django setup in windows
  • how to change django admin text
  • override django allauth
  • python render_template
  • handle queries in ListView django
  • on_delete=models.cascade
  • heroku django procfile
  • Datetime format django rest framework
  • insert data in django models
  • django app
  • user login validation django
  • django login
  • db_index django
  • from django.contrib import messages
  • django rest framework send email
  • bulk create django
  • django set session variable
  • retrieve object from context in django
  • django meta attributes
  • django group by
  • set form field disabled django
  • what does class meta do in django
  • django today date in template
  • get_or_create in django
  • mongo db python
  • Install Django in Windows
  • install django
  • or operator in django queryset
  • django static files / templates
  • django static files
  • how to check django rest framework version
  • django change user password
  • how to create requirements.txt django
  • django content type
  • django set default value for model not form
  • django updateview
  • django ajax body to json
  • cannot import name 'httpresponse' from 'django.http'
  • django view
  • import http response in django
  • how to add phone number to django user model
  • django custom primary key field
  • django model UUID field
  • check if the user is logged in django decorator
  • django download
  • django latest version
  • django ModelChoiceField value not id
  • django reverse queryset
  • get csrf_token value in django template
  • redirect to the same page django
  • django versatileimagefield
  • django.db.utils.ProgrammingError: relation "users" does not exist in django 3.0
  • django logger
  • import csrf_exempt django
  • django migrate fake zero
  • django orm
  • django q objects
  • django in conda
  • django admin register
  • django get parameters from url
  • django filter by date range
  • django refresh form db
  • csrf token fetch django
  • django choice field
  • django model current timestamp
  • django orm timestamp field
  • set django static root
  • else if in django template
  • heroku requirements.txt python
  • django get all model fields
  • django iterate over all objects
  • get context data django
  • django channels jwt auth
  • django paginator code
  • django rest framework viewset perform_update
  • django basic steps
  • foreginkey django
  • @transactional annotation
  • set http response content type django
  • related name in django
  • python MongoEngine doc
  • django redirect to external url
  • management commands django
  • apiview django
  • filter startswith django
  • extract email address using expression in django
  • django pandas queryset
  • loginrequiredmixin
  • raw query in django
  • django query multiple conditions
  • django signals post_save not working
  • django signals post save recursion
  • django signals post save repeat
  • django post_save update_fields
  • image in django
  • from django.contrib.auth.decorators import authenticate, login
  • django queryset group by count
  • django model plural
  • django change password command line
  • Django Change Password
  • how to reset username and password in django admin
  • plural name django
  • where django do you get decorators
  • radiobuttons django
  • django password field
  • django only certain columns from database
  • django slug int url mapping
  • django id
  • django staff_member_required decorator
  • django display view library
  • import abstractuser
  • filter django or
  • how to bulk update in mongodb using python
  • django set random password
  • startapp django
  • create a queryset list django
  • summation django queryset
  • create fixtures django
  • decimal places django template
  • django json field
  • logging in django
  • how to set up django rest framework in
  • create django group
  • How to get current page url in django template
  • where to import render in django
  • django model example
  • django template iterate dict
  • django sites framework
  • include one django template
  • conda import django
  • django queryset first element
  • add row in db django
  • django rest framework default_authentication_classes
  • django datepicker
  • creating base models django
  • djangodebug toolbar not showing
  • django run management command from code
  • latest django version
  • use django taggit in template
  • sqlalchemy one to many
  • django check if model field is empty
  • django bulk update
  • serialization in django
  • pass in queryset as filter django
  • django model form
  • gitignore django
  • django gitignore
  • delete and start fresh with db django
  • request.build_absolute_uri django
  • query set
  • django loginview?
  • Standard Django URL
  • django form view
  • django connection cursor
  • django form_valid
  • unique_together what is used of it in django
  • django bootstrap
  • windows 10 reset django migrations
  • Django print query
  • Comment voir les requêtes SQL brutes exécutées par Django?
  • packet tracer
  • django admin required decorator
  • django login required decorator
  • python generate requirements.txt
  • how to check django version
  • Django Forms
  • check django version windows
  • django forms
  • django create user
  • change django administration text
  • djanog admin cookbook change text
  • Add help text in Django model forms
  • django get or create object
  • django forms request
  • django templates config
  • django admin image
  • django charfield force lowercase
  • django form set min and max value
  • how to delete django superuser
  • show all urls django extensions
  • django signals
  • django not saving images forms
  • django import json
  • how to connect templates in django
  • django edit profile
  • django crispy forms foundation for site
  • update a package with pip in django
  • django start python function when pressing button
  • django delete session
  • user passes test django
  • FormView API
  • formview django
  • django insert bulk data
  • django httpresponseredirect reverse app url
  • messages in django
  • django cheat sheet pdf
  • message tags in django
  • django forms error customize
  • how to get user id django
  • get user django
  • mongodb in python
  • where to import reverse_lazy in django
  • serializers.validationerror django
  • httpresponse django
  • django template render dictionary
  • how to create urls in django
  • merge two query sets django
  • django rest api using files
  • create views django
  • search in django
  • django sessions for beginners
  • how to create a website with django
  • create django project
  • django start app
  • servereur nmanage
  • createapp cammand in django
  • django channel
  • kill port django
  • django model query join
  • adding static file and its usage in Django
  • how to register - paginate tag in django
  • django paginator
  • django pagination class based views
  • from django.db import models
  • arrayfield django example
  • super in django manager
  • django manger
  • django manager
  • views django
  • django foreign key field
  • django queryset last 10
  • django import settings variables
  • django model choice field from another model
  • django serve media folder
  • collections counter
  • .first() in django
  • django queryset to form
  • ModelForm
  • Check django version in your system
  • djanog userformcreation message
  • jsonresponse django
  • template tags in django
  • django add to database
  • make value of two tables unique django
  • from import execute_from_command_line ImportError: No module named
  • csrf token django
  • in function how to get data from django form
  • mongoengine
  • da
  • Postgres Database Django
  • python django query
  • request headers in Django
  • objects.filter django
  • what is queryset in django
  • listing of django model types
  • django update
  • django email change sender name
  • django timezone settings
  • django choicefield empty label
  • django sumernote
  • render to response django
  • django generate openapi schema command line
  • get_absolute_url django
  • User serializer in django rest framework
  • django models
  • What are models
  • django models filter
  • django authenticate with email
  • create jwt token in django
  • launch sqlite django
  • django migrate
  • django group with permission
  • django check user admin
  • django form field class
  • django
  • django or
  • django get current user in form
  • start a django project
  • static file link in django
  • django operational error
  • what is NoReverseMatch in django?
  • adding extra fields to user model django
  • django with mongodb
  • django template for loop
  • fetch json array from mysql django
  • django builtin signals
  • login url
  • django login url
  • django check if user is staff in template
  • django create multiple objects
  • django queryset exists
  • django query string route
  • migrations.rename_field django
  • django console
  • how to extract field values in list from queryset in django
  • django form list option
  • django wait for database
  • check this id exist in database django
  • django from
  • django redis install
  • django pass list of fields to values
  • how to send file in django response
  • add template folder in django
  • restfull api in django
  • django user permission check
  • simple django app
  • float number field django models
  • django notes
  • pass context data with templateview in django
  • disable csrf token django
  • django on delete set default
  • django order by foreign key count
  • django querset group by sum
  • making ckeditor django responsive
  • django queryset group by sum
  • django get latest object
  • django orm group by month and year
  • django show image in admin page
  • management command in django
  • django content type for model
  • what is a serializer django
  • django 3 create async rest api
  • genrate random code in django
  • extra import on django
  • where to import messages in django
  • redirect if not logged in django
  • run django localhost server
  • migrate data django

7815 7816 7817 7818 7819