describes a way to run an ORM operation in a py script :
You can create a new py file within your project to copy the following code in the manage.py file in your project :
if __name__ = = "__main__":
Os.environ.setdefault ("Django_settings_module", "orm1.settings")
Import Django # manually add imports
Django.setup () # start
Form APP01 Import Models # imports from within the project app models
then you can operate it in the right-click mode . ORM Statement .
a . must be the method of the article :
1. Models. Book.objects.all () # gets all the book objects , The result is the object list
2. Models. Book.objects.get ( condition ) # Get an object that meets the criteria
3. Models. Book.objects.filter ( condition ) # Filter all eligible , result is Object list
4. Models. Book.objects.exclude ( condition ) # filters out all non-conforming , The result is the object list
5. Models. Book.objects.all (). VALUES () # Dictionary list , [{id:1,name:20}, {id:2,name:18}]
The values (' ID ') are not specified in parentheses, display all , as specified, only the specified , [{id:1}, {id:2,}]
6. Models. Book.objects.all (). Values_list () # tuple list , [(1,20), (2,18)] ditto , display specified when specified
7. Models. Book.objects.all (). order_by (' id ') # sort rows by ID Ascending
Models. Book.objects.all (). order_by ('-id ') # sort rows by ID Descending
Models. Book.objects.all (). order_by (' age ', '-id ') # first by age ascending , age same by ID Sort in descending order
8. Models. Book.objects.all (). order_by (' id '). reverse () # Reverses the result ; Note Reverse must be sorted before ,
otherwise Reverse Invalid ; or in model.py in the file Book in the class Meta specified in ordering= (' id ',) Note that commas must have
9. Distinct (): # Go heavy , when the results obtained Queryset The same object appears multiple times in the list , leaving only one
Ten. Models. Book.objects.all (). Count () # counts the number of results that can be counted , such as the Queryset the number of elements in the statistics .
One by one. Models. Book.objects.all (). First () # Gets the number one in the result , Even if the previous result list is empty , no error
Models. Book.objects.filter (). Last () # gets the final bar in the result
13.models. Book.objects.filter (). Exists () # determine If there is something in the Queryset list, and The result is True or False;
two . summary :
return to List of objects (Queryset) the method has :
All () filter () ordey_by () Exclude () VALUES () values_list () reverse () distinct ()
the methods for returning a single object are :
First () Last () get () Create () creates an object and returns the object that was just created
the Boolean values are judged by :
Exists ()
The numbers returned are :
Count ()
13 Ways to use ORM