Basic operations
<1> All (): Query All Results <2> filter (**kwargs): It contains objects <3> get (**kwargs) that match the given filter criteria: Returns an object that matches the filter criteria given, with only one result returned, and if more than one object meets the filter criteria or no error is thrown. <4> Exclude (**kwargs): It contains objects that do not match the given filter criteria <5> values (*field): Returns a valuequeryset--a special queryset , it is not an instantiated object of a series of model, but an iterative dictionary sequence <6> values_list (*field): It is very similar to the values (), it returns a tuple sequence, Values return a dictionary sequence <7> order_by (*field): Sort the results of the query <8> reverse (): reverse-sort the results of the query, note reverse () You can usually only call on a queryset that has a defined order (specify ordering in the meta of the model class or call the Order_by () method). <9> distinct (): eliminate duplicate records from the returned results (if you query across multiple tables, you may get duplicate results when you calculate queryset.) You can use DISTINCT () at this point, and note that you only support by field to weight in PostgreSQL. <10> count (): Returns the number of objects in the database that match the query (QuerySet). <11> First (): return to record one <12> last (): return final record <13> exists (): returns True if Queryset contains data otherwise returns false
Classification by return value
The method that returns the Queryset object has all () filter () Exelude () order_by () reverse () distinct () Special querysetvalues () to return an iterative dictionary sequence Values_ List () returns an iterative sequence of ganso that returns a specific object by the Get () first () last () method that returns a Boolean value that has the method of exists () that returns a number with count ()
Double underline operation
Models. Tb1.objects.filter (id__lt=10, id__gt=1) # Gets the value models with an ID greater than 1 and less than 10. Tb1.objects.filter (id__in=[11, +) # Gets the data models ID equals 11, 22, 33. Tb1.objects.exclude (id__in=[11, [+]) # in models. Tb1.objects.filter (name__contains= "ven") # Gets the name field models that contains "ven". Tb1.objects.filter (name__icontains= "Ven") # Icontains case insensitive models. Tb1.objects.filter (Id__range=[1, 3]) # ID range is 1 to 3, equivalent to SQL Bettwen and similar also: Startswith,istartswith, EndsWith, The Iendswith date field can also: models. Class.objects.filter (first_day__year=2017)
ForeignKey operation forward Lookup object lookup (cross-table)
Syntax: object . The associated field . Field
Example:
Book_obj = models. Book.objects.first () # First book object print (Book_obj.publisher) # Get this book associated publishing house Object print (Book_obj.publisher.name) # Get the name of the Publisher object
Field lookup (cross-table)
Syntax: associated field __ field
Example:
Print (models. Book.objects.values_list ("Publisher__name"))
Reverse manipulating object Lookups
Syntax: obj. Table name _set
Example:
Publisher_obj = models. Publisher.objects.first () # Find the first Publisher object books = Publisher_obj.book_set.all () # Find all books published by the first publishing house titles = Books.values_list ("title") # Find the title of all books published by the first publishing house
Field Lookup
Syntax: Table name __ Field
Example:
Titles = models. Publisher.objects.values_list ("Book__title")
Manytomanyfieldclass Relatedmanager
The Association manager is a manager that is used in a one-to-many or many-to-many association contexts.
It exists in the following two scenarios:
- Reverse query for foreign key relationships
- Many-to-many association relationships
Simply put, you can use the following method when the object behind the point may be multiple.
Method
Create ()
Creates a new object, saves the object, and adds it to the set of associated objects, returning the newly created object.
>>> Import datetime>>> models. Author.objects.first (). Book_set.create (title= "Tomato", publish_date=datetime.date.today ())
Add ()
Adds the specified model object to the associated object set.
adding objects
>>> AUTHOR_OBJS = models. Author.objects.filter (id__lt=3) >>> models. Book.objects.first (). Authors.add (*AUTHOR_OBJS)
Add ID
>>> models. Book.objects.first (). Authors.add (*[1, 2])
Set ()
Updates the associated object of the model object.
>>> book_obj = models. Book.objects.first () >>> Book_obj.authors.set ([2, 3])
Remove ()
To remove an executed model object from the associated object set
>>> book_obj = models. Book.objects.first () >>> Book_obj.authors.remove (3)
Clear ()
Removes all objects from the associated object set.
>>> book_obj = models. Book.objects.first () >>> book_obj.authors.clear ()
Attention:
For ForeignKey objects, the Clear () and remove () methods exist only at null=true time.
As an example:
ForeignKey field is not set Null=true,
Class book (Models. Model): title = models. Charfield (max_length=32) publisher = models. ForeignKey (To=publisher)
There is no clear () and remove () method:
>>> models. Publisher.objects.first (). Book_set.clear () Traceback (most recent): File ' <input> ', line 1, in < Module>attributeerror: ' Relatedmanager ' object has no attribute ' clear '
When the ForeignKey field is set to Null=true,
Class book (Models. Model): name = models. Charfield (max_length=32) publisher = models. ForeignKey (To=class, Null=true)
The clear () and remove () methods are now available:
>>> models. Publisher.objects.first (). Book_set.clear ()
Note: For all types of associated fields, add (), create (), remove (), and Clear (), set () will update the database immediately. In other words, there is no need to call the Save () method at either end of the association.
Aggregation and grouping query aggregation
aggregate () is a terminating clause in QuerySet , meaning that it returns a dictionary containing some key-value pairs.
The name of the key is an identifier for the aggregated value, and the value is the computed aggregate value. The name of the key is automatically generated by the name of the field and aggregate function.
Example:
>>> models. Book.objects.all (). Aggregate (AVG ("price")) {' Price__avg ': 13.233333}
If you want to specify a name for the aggregation value, you can provide it to the aggregation clause.
>>> models. Book.objects.aggregate (Average_price=avg (' price ')) {' Average_price ': 13.233333}
If you want to generate more than one aggregation, you can add another parameter to the aggregate () clause. So, if you also want to know the maximum and minimum value of all book prices, you can query:
>>> models. Book.objects.all (). Aggregate (AVG ("Price"), Max ("Price"), Min ("price")) {' Price__avg ': 13.233333, ' Price__max ': Decimal (' 19.90 '), ' price__min ': decimal (' 9.90 ')}
Group
Generates a separate statistic value for each object in the Queryset that is called.
Example 1: Count the number of authors per book
>>> book_list = models. Book.objects.all (). Annotate (Author_num=count ("author")) >>> for obj in book_list: ... Print (Obj.author_num) ... 211
Example 2: Statistics The price of the cheapest book bought by each publishing house
>>> publisher_list = models. Publisher.objects.annotate (Min_price=min ("Book__price")) >>> for obj in publisher_list: ... Print (Obj.min_price) ... 9.9019.90
Method Two:
>>> models. Book.objects.values ("Publisher__name"). Annotate (Min_price=min ("price")) <queryset [{' Publisher__name ': ' Shahe Press ' , ' Min_price ': decimal (' 9.90 ')}, {' Publisher__name ': ' Publishing house ', ' Min_price ': decimal (' 19.90 ')}]>
Example 3: A book that counts more than one author
>>> models. Book.objects.annotate (Author_num=count ("author")). Filter (Author_num__gt=1) <queryset [<book: Tomato >]>
Example 4: Sort query set QuerySet based on the number of book authors
>>> models. Book.objects.annotate (Author_num=count ("author")). Order_by ("Author_num") <queryset [<book: Banana object language;, < Book: The orange Thing language, <book: Tomato thing language >]>
Example 5: Query the total price of each author's book
>>> models. Author.objects.annotate (Sum_price=sum ("Book__price")). VALUES ("name", "Sum_price") <queryset [{' Name ': ' Elf ', ' Sum_price ': Decimal (' 9.90 ')}, {' name ': ' Little fairy ', ' Sum_price ': decimal (' 29.80 ')}, {' name ': ' Little Witch ', ' Sum_price ': decimal (' 9.90 ')}]>
F Query and Q query f query
In all of the above examples, the filters we construct simply compare the field values to a constant. What if we were to compare the values of two fields?
Django provides F () to make such comparisons. An instance of F () can reference a field in a query to compare the values of two different fields in the same model instance.
Example 1:
Search for books with more than the number of comments
From Django.db.models import Fmodels.Book.objects.filter (commnet_num__lt=f (' Keep_num '))
Django supports subtraction and modulo operations between f () objects and between f () objects and constants.
Models. Book.objects.filter (commnet_num__lt=f (' Keep_num ')
The modify operation can also use the F function, for example, to increase the price of each book by 30 yuan
Models. Book.objects.all (). Update (Price=f ("price") +30)
Extended:
What if you want to modify the Char field?
such as: Add all the titles (first edition)
>>> from django.db.models.functions import concat>>> from django.db.models import value>>> Models. Book.objects.all (). Update (Title=concat (F ("title"), Value ("("), Value ("first version"), Value (")"))
Q Query
The keyword parameter queries in methods such as filter () are all "and" together. If you need to perform more complex queries (such as an OR statement), you can use the Q object .
Example 1:
Query author name is a fairy or a little witch
Models. Book.objects.filter (Q (authors__name= "Little Fairy") | Q (authors__name= "Little Witch"))
You can combine & and | Operators and use parentheses to group them to write arbitrarily complex Q objects. at the same time, theQ object can be reversed using the ~ operator, which allows the combination ofnormal query and inverse (not) queries.
Example: The query author name is the little fairy and is not the title of the book published in 2018.
>>> models. Book.objects.filter (Q (author__name= "Little Fairy") & ~q (publish_date__year=2018)). Values_list ("title") <queryset [(' Tomato ","]>
Query functions can be mixed using the Q object and the keyword parameters. all arguments (keyword arguments or Q objects) that are provided to the query function are "and" together. However, if the Q object appears, it must precede all the keyword parameters.
For example: The year of inquiry publication is 2017 or 2018, all books with the book of words in the title.
>>> models. Book.objects.filter (Q (publish_date__year=2018) | Q (publish_date__year=2017), title__icontains= "Things") <queryset [<book: Tomato, <book: Banana object language;, <book: The orange thing language >]>
Transaction
Import osif __name__ = = ' __main__ ': os.environ.setdefault ("Django_settings_module", "bms.settings") Import Django django.setup () import datetime from APP01 import models try: from django.db Import Transaction with transaction.atomic (): New_publisher = models. Publisher.objects.create (name= "Mars publishing House") models. Book.objects.create (title= "Orange Object", Publish_date=datetime.date.today (), publisher_id=10) # Specify a publisher ID that does not exist Except Exception as E: print (str (e))
Django ORM for database operations