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

# perhaps 
user = User(username=xxx,password=xxx,email=xxx,phone=xxx)
 Copy code 

Can be in Django shell Middle attempt , After the code is changed, you need to re-enter

python3 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 
# Back to QuerySet Is a tuple list 

# 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
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 
# 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__in=["jack","tom"])# Is it within the scope of 
 Copy code 

to update

# Update an object 
obj = User.objects.get(username="jack")
obj.age = 30

# Batch update 
queryset = User.objects.filter(age__gt=5)
 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/{{ }}"> to update <a href="book/delete/{{ }}"> Delete

input Input components : It can't be edited ,disabled="disabled" No submission , Not set up name attribute


# Delete a single object 
obj = User.objects.get(username="jack")

# Batch deletion 
queryset = User.objects.filter(age__lt=5)

# 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 

Last one :Django Model class 1

copyright notice
author[laufing],Please bring the original link to reprint, thank you.

Random recommended