CRUD of model classes

Increase the data

Use the object manager of the model class objects.create
User.objects.create(username=xxx,password=xxx,email=xxx,phone=xxx)

# or
user = User(username=xxx,password=xxx,email=xxx,phone=xxx)
user.save()
Copy the code

You can try it in your Django shell, re-entering it after code changes

python3 manage.py shell
>>from user.models import User
Copy the code

The query

User.objects.all(a)# query all data -->QuerySet object to iterate over each data object

The QuerySet is a list of dictionaries
User.objects.values('col1'."col2",...).The QuerySet returned is a list of tuples
User.objects.values_list("col1"."col2")

# sort
User.objects.order_by("-age") # descending, default ascending
User.objects.values("username".'age').order_by("age".'-xx') # in ascending order by ageQuerySet objects. The queryGet the SQL statement
Copy the code

Exercise, configure a route /user/all, request mode GET, view, show_all

#views.py
def show_all(request) :
	users = User.objects.all(a)return render(request,"index.html".locals())
Dictionary of local variables for #locals()
Copy the code

Make the front end display all user data in tabular form

Conditions of the query

User.objects.filter(username="jack",age=12) # multiple conditional and join, return QuerySet object

# delete query
User.objects.exclude(username="jack")Return QuerySet to exclude data for this condition

Get an object, return an object
User.objects.get(username="jack") 
SQL > query multiple objects
# Error without data

# query predicateThe field __ predicate user.objects.filter(id__exact=1) With id # 1
User.objects.filter(id__gt=1) #id>1
User.objects.filter(id__lte=5) #id<=5
User.objects.filter(username__exact="jack") # username for jack
User.objects.filter(username__contains="jack")#username contains jack
User.objects.filter(username__startswith="j") # starts with j
User.objects.filter(username__endswith="k")
User.objects.filter(username__in=["jack"."tom"])# Is within the range
User.objects.filter(age__range=(25.35))
Copy the code

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 the code

On the basis of displaying user information in table form, the user information is updated and two buttons are deleted. < a href = “book/update / {{obj. Id}}” > update < a href = “book/delete / {{obj. Id}}” > delete

Input Input component: not editable, disabled=”disabled” No submission, no name property

delete

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

# batch delete
queryset = User.objects.filter(age__lt=5)
queryset.delete()

# fake delete, do not really delete data
is_delete = models.BooleanField("Delete or not",default=False)
Select * from is_delete where is_delete is False
Copy the code

Django model Class 1 Django Model Class 3