Django ORM operations

Source: Internet
Author: User

Official documentation

I. general operations
All () query all results filters (** kwargs). It contains the get (** kwargs) object that matches the given filter conditions) returns an object that matches the given filtering condition. Only one of the returned results is returned. If more than one or none of the objects meet the filtering condition, an error exclude (** kwargs) is thrown) it contains the values (* fields) object that does not match the given filtering condition and returns a valuequeryset -- a special queryset. After running, it does not obtain a series of model instantiation objects, it is an iterative dictionary sequence values_list (* fields). It is very similar to values (). It returns a sequence of tuples, and values returns a sequence of dictionary order_by (* fields) sort query results reverse () sorts query results in reverse order. Note that reverse () can only be called on queryset with a defined order (specify ordering in the meta of the model class ). Alternatively, you can call the order_by () method) distinct () to remove duplicate records from the returned results. (If you query multiple tables, you may obtain duplicate results during queryset calculation. In this case, you can use distinct (). Note that only PostgreSQL supports deduplication by field.) count () returns the number of objects matching the query (queryset) in the database first () returns the first record last (). returns the last record exists (). returns true if queryset contains data; otherwise, returns false.

Queryset Method


Two special methods for returning queryset

Values () returns an iterative dictionary sequence values_list () and returns an iterative ancestor sequence.
Models. publisher. objects. values ("name") # <queryset [{'name': 'shanghai Publishing House '}, {'name': 'lijiang Publishing House'}]> models. publisher. objects. values_list ("name") # <queryset [('shanghai Publishing House ',), ('lijiang Publishing House',)]> # query all fields without field names.

Methods for returning specific objects in the database


Return Boolean value: exists ()

obj = models.Publisher.objects.exists()print(obj)  # True

Return number: Count ()

Double underscores in a single table Query
Models. tb1.objects. filter (ID _ lt = 10, ID _ GT = 1) # obtain the value models with ID greater than 1 and less than 10. tb1.objects. filter (ID _ in = [11, 22, 33]) # obtain data models with IDs equal to 11, 22, and 33. tb1.objects. exclude (ID _ in = [11, 22, 33]) # obtain data models with IDs except 11, 22, and 33. tb1.objects. filter (name _ contains = "ven") # obtain the data models whose name field contains "ven. tb1.objects. filter (name _ icontains = "ven") # The first one is I, which is case-insensitive. For example, models can be obtained for "ven", "ven", and "ven. tb1.objects. filter (ID _ range = [1, 3]) # obtain data with IDs ranging from 1 to 3. Similar to bettwen and in SQL, startswith, istartswith, endswith, the iendswithdate field can also be: models. class. objects. filter (birthday _ year = 2018)

Ii. foreignkey operation 2.1 forward lookup

2.1.1 Object Search (cross-table)

Syntax: object. associated field. Field

Book_obj = models. Book. Objects. First () # print (book_obj.publisher) # obtain the print ( object associated with this book # obtain the name of the Publisher Object

2.1.2 field search (cross-table)

Syntax: Join field _

Pub_obj = models. Book. Objects. values_list ("publisher _ name") [0] print (pub_obj [0]) # Beijing Press
2.2 Reverse Lookup

2.2.1 Object Search

Syntax: obj. Table name_set

Pub_obj = models. publisher. objects. first () # Find the first Publisher Object book = pub_obj.book_set.all () # Find all the books published by the first publisher print (book) # <queryset [<book: book Object>]> Title = book. values_list ("title") # Find the title print (title) of all the books published by the first publishing house # <queryset [('shaded sky',)]>

PS:If you set it as follows, you do not need to useOBJ. Table name_set,OBJ. Table NameYou can.

# Book = pub_obj.book_set.all () # change to book = ()

2.2.2 field search

Syntax: Table name__field

book_obj_title = models.Publisher.objects.values_list("book__title")
3. manytomanyfield operation class relatedmanager

"Association manager" is the manager used in one-to-many or multiple-to-many association context.

It exists in the following two situations:

  • Reverse query of foreign key relationships
  • Multi-to-Multi-Association

Simply put, you can use the following method when there may be multiple objects after a vertex.


Create ()

Create a new object, save the object, add it to the associated object set, and return the newly created object.

# If you create a book by the author, author_obj = models will be automatically saved. author. objects. first () (Title = "Python", price = 99, store = 100, sale = 10, publisher_id = 2)

Add ()

Add the specified model object to the correlated object set.

Add an existing book to the author:

author_obj = models.Author.objects.filter(id=5)[0]book = models.Book.objects.filter(id=4)[0]

Add multiple existing books to the author:

author_obj = models.Author.objects.filter(id=3)[0]book = models.Book.objects.filter(id__gt=6)*book)

Add the book id directly

author_obj = models.Author.objects.filter(id=2)[0]*[1,2])

Set ()

Update (reset) the associated object of the model object.

author_obj = models.Author.objects.first()[4,5])

Remove ()

Removes the executed model object from the correlated object set.

author_obj = models.Author.objects.filter(id=1)[0]

Clear ()

Removes all objects from the correlated object set.

author_obj = models.Author.objects.filter(id=2)[0]


For foreignkey objects, the clear () and remove () methods only exist when null = true.


When the foreignkey field is not set to null = true, the clear () and remove () methods are not available:

class Book(models.Model):    title = models.CharField(max_length=32)    publisher = models.ForeignKey(to="Publisher")
>>>models.Publisher.objects.first().book_set.clear()Traceback (most recent call last):  File "E:/untitled/", line 12, in <module>    models.Publisher.objects.first().book_set.clear()AttributeError: ‘RelatedManager‘ object has no attribute ‘clear‘

When the foreignkey field is set to null = true, the clear () and remove () methods are available:


The code above indicates that the Publisher Object is obtained, and then the reverse operation is performed to clear all the books published by the publisher. That is, the publisher_id of the books originally published by the publisher is set to null.


For all types of associated fields, add (), create (), remove (), clear (), and set () will immediately update the database. In other words, you do not need to call the SAVE () method at any end of the association.




























































Django ORM operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.