current position:Home>Django model class 2
Django model class 2
2022-01-31 05:37:09 【laufing】
Model class CRUD
Add data
# Use the object manager of the model class objects.create
User.objects.create(username=xxx,password=xxx,email=xxx,phone=xxx)
# perhaps
user = User(username=xxx,password=xxx,email=xxx,phone=xxx)
user.save()
Copy code
Can be in Django shell Middle attempt , After the code is changed, you need to re-enter
python3 manage.py shell
>>from user.models import User
Copy code
Inquire about
User.objects.all() # Query all the data -->QuerySet object , Traverse to get each data object
# Take values according to fields , Back to QuerySet For the dictionary list
User.objects.values('col1',"col2",...)
# Back to QuerySet Is a tuple list
User.objects.values_list("col1","col2")
# Sort
User.objects.order_by("-age") # Descending , Default ascending order
User.objects.values("username",'age').order_by("age",'-xx') # according to age Ascending
QuerySet object .query # Get sql sentence
Copy code
practice , Configure a route /user/all, Request mode GET, View ,show_all
#views.py
def show_all(request):
users = User.objects.all()
return render(request,"index.html",locals())
#locals() Dictionary of function local variables
Copy code
Let the front end display all user data in tabular form
Conditions of the query
User.objects.filter(username="jack",age=12) # Multiple conditions and Connect , return QuerySet object
# Exclude queries
User.objects.exclude(username="jack")# Data excluding this condition , return QuerySet
# Get an object , Returns the object
User.objects.get(username="jack")
# Query multiple objects , Report errors
# If there is no data, an error will be reported , Pay attention to exception capture
# query predicate
Field __ The predicate
User.objects.filter(id__exact=1) #id by 1
User.objects.filter(id__gt=1) #id>1
User.objects.filter(id__lte=5) #id<=5
User.objects.filter(username__exact="jack") #username by jack
User.objects.filter(username__contains="jack")#username Contained in the jack
User.objects.filter(username__startswith="j") # With j At the beginning
User.objects.filter(username__endswith="k")
User.objects.filter(username__in=["jack","tom"])# Is it within the scope of
User.objects.filter(age__range=(25,35))
Copy code
to update
# Update an object
obj = User.objects.get(username="jack")
obj.age = 30
obj.save()
# Batch update
queryset = User.objects.filter(age__gt=5)
queryset.update(age=20)
Copy code
On the basis of displaying user information in tabular form , Complete the update of user information , Delete the function of two buttons . <a href="book/update/{{ obj.id }}"> to update <a href="book/delete/{{ obj.id }}"> Delete
input Input components : It can't be edited ,disabled="disabled" No submission , Not set up name attribute
Delete
# Delete a single object
obj = User.objects.get(username="jack")
obj.delete()
# Batch deletion
queryset = User.objects.filter(age__lt=5)
queryset.delete()
# Pseudo delete , Don't really delete data
is_delete = models.BooleanField(" Whether or not to delete ",default=False)
# When querying data , Query only is_delete by False The data of
Copy code
copyright notice
author[laufing],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201310537073590.html
The sidebar is recommended
- My friend's stock suffered a terrible loss. When I was angry, I crawled the latest data of securities with Python
- Python interface automation testing framework -- if you want to do well, you must first sharpen its tools
- Python multi thread crawling weather website pictures and saving
- How to convert pandas data to excel file
- Python series tutorials 122
- Python Complete Guide - printing data using pyspark
- Python Complete Guide -- tuple conversion array
- Stroke the list in python (top)
- Analysis of Python requests module
- Comments and variables in Python
guess what you like
-
New statement match, the new version of Python is finally going to introduce switch case?
-
Fanwai 6 Different operations for image details in Python opencv
-
Python crawler native code learning (I)
-
Python quantitative data warehouse building series 2: Python operation database
-
Python code reading (Part 50): taking elements from list intervals
-
Pyechart + pandas made word cloud pictures of 19 report documents
-
[Python crawler] multithreaded daemon & join() blocking
-
Python crawls cat pictures in batches to realize thousand image imaging
-
Van * Python | simple crawling of a planet
-
Input and output of Python practice
Random recommended
- Django ORM details - fields, attributes, operations
- Python web crawler - crawling cloud music review (3)
- Stroke list in python (bottom)
- What cat is the most popular? Python crawls the whole network of cat pictures. Which one is your favorite
- [algorithm learning] LCP 06 Take coins (Java / C / C + + / Python / go / trust)
- Python shows the progress of downloading files from requests
- Solve the problem that Django celery beat prompts that the database is incorrectly configured and does not support multiple databases
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python quantitative data warehouse construction 3: data drop library code encapsulation
- The source code and implementation of Django CSRF Middleware
- Python hashlib module
- The cover of Python 3 web crawler development (Second Edition) has been determined!
- The introduction method of executing Python source code or Python source code file (novice, please enter the old bird and turn left)
- [Python basics] explain Python basic functions in detail, including teaching and learning
- Python web crawler - crawling cloud music review (4)
- The first step of scientific research: create Python virtual environment on Linux server
- Writing nmap scanning tool in Python -- multithreaded version
- leetcode 2057. Smallest Index With Equal Value(python)
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python crawler actual combat, requests module, python realizes capturing a video barrage
- [algorithm learning] 1108 IP address invalidation (Java / C / C + + / Python / go / trust)
- Test platform series (71) Python timed task scheme
- Java AES / ECB / pkcs5padding encryption conversion Python 3
- Loguru: the ultimate Python log solution
- Blurring and anonymizing faces using OpenCV and python
- How fast Python sync and async execute
- Python interface automation test framework (basic) -- common data types list & set ()
- Python crawler actual combat, requests module, python realizes capturing video barrage comments of station B
- Python: several implementation methods of multi process
- Sword finger offer II 054 Sum of all values greater than or equal to nodes | 538 | 1038 (Java / C / C + + / Python / go / trust)
- How IOS developers learn python programming 3-operator 2
- How IOS developers learn python programming 2-operator 1
- [Python applet] 8 lines of code to realize file de duplication
- Python uses the pynvml tool to obtain the working status of GPU
- Data mining: Python actual combat multi factor analysis
- Manually compile opencv on MacOS and Linux and add it to Python / C + + / Java as a dependency
- Use Python VTK to batch read 2D slices and display 3D models
- Complete image cutting using Python version VTK
- Python interface automation test framework (basic) -- common data types Dict
- Python specific text extraction in actual combat challenges the first step of efficient office