Django Web development model operation

model operation

deletions in the database is used to check the operation corresponding to the model change
reference document https://docs.djangoproject.com/zh-hans/2.2/topics/db/models/

Sample file

from django.db import models

class Students(models.Model):
    """学生表"""
    username = models.CharField(max_length=64, null=False, unique=True)
    age = models.IntegerField()
    cls = models.ForeignKey('ClassInfo', on_delete=models.DO_NOTHING)


class ClassInfo(models.Model):
    """班级表"""
    title = models.CharField(max_length=64, null=False, unique=True)
    teachers = models.models.ManyToManyField("Teachers")


class Teachers(models.Model):
    """老师表"""
    name = models.CharField(max_length=16, null=False, unique=True)

1. Single table operation

1.1 Add data

  • The first way
obj = models.Students(username='张三', cls_id='1')
obj.save()
  • The second way
models.Students.objects.create(username='张三', cls_id='1)

1.2 Query data

  • get
# 获取id为1的学生
models.Students.objects.get(id='1')
  • filter acquisition
# 查询id=1的学生
obj = models.Students.objects.filter(id='1')
# 查询年龄大于19的学生
obj = models.Students.objects.filter(age__gt=19)
# 查询年龄大于19小于22的学生
obj = models.Students.objects.filter(age__gt=19, age__lt=22)
# 查询id在[1, 3, 5, 6]的学生
obj = models.Students.objects.filter(id__in=[1, 3, 5, 6])
# 查询名字包含“伟”的学生
obj = models.Students.objects.filter(username__contains=='伟')

  • all () query all
stu_list = models.Students.objects.all()  # 返回查询集,里面都是对象
  • vlaues
stu_list = models.Students.objects.values()   # 返回查询机,里面都是字典,不写字段,默认显示错有
  • vlaues_list
stu_list = models.Students.objects.values_list()   # 返回查询机,里面都是元组

1.3 Modify the data

  • update
# 修改id为1的学生的班级
obj = models.Students.objects.filter(id='1') # 通过查询找到id为1的学生
obj.update(cls_id=2) # 使用update更新该学生信息

1.4 Delete data

# 修改id为1的学生的班级
obj = models.Students.objects.filter(id='1') # 通过查询找到id为1的学生
obj.delete() # 使用delete() 删除

1.5 query set

Query function

Function name Features return value Explanation
get Return one item in the table that satisfies the condition and only one piece of data The return value is a model object The query conditions are written in the parameters. 1) If multiple data are found, an exception MultipleObjectsReturned is thrown. 2) If the data cannot be queried, an exception is thrown: DoesNotExist.
all Returns all data in the table corresponding to the model class. The return value is of type QuerySet Query set
filter Returns data that meets the conditions. The return value is of type QuerySet Parameters write query conditions.
exclude Return data that does not meet the conditions. The return value is of type QuerySet Parameters write query conditions.
order_by Sort the query results. The return value is based on which fields are sorted in the QuerySet type parameter.

All, filter, exclude, order_by call these functions will generate a query set, QuerySet class objects can continue to call all the above functions.

Query set characteristics
1) Lazy query: Only when the data in the query set is actually used will the real query to the database occur.
2) Cache: When the same query set is used, the actual database query will occur when it is used for the first time, and then the results will be cached. When the query set is used later, the results in the cache are used.
3) Subscripting or slicing operations can be performed on a query set to limit the results of the query set, similar to lists. Slicing a query set will result in a new query set, and subscripts are not allowed to be negative.

2. Association operation

2.1 One-to-many operation

Students and classes are in a one-to-many relationship, one student corresponds to one class, and one class corresponds to multiple students

Find the class title through students

stu_obj = model.Stuents.objects.get(id=1)
cls_title = stu_obj.cls.title

## 使用双下划线方式
cls_obj = model.Stuents.objects.filter(id=1).values_list("classinfo__title")

Query all students in Grade 1 Class 1

cls_obj = models.ClassInfo.objects.filter(title='1年级1班')
stu_list = cls_obj.students_set.all()

2.2 Many-to-many operation

create

# 为1年级1班新建一名老师
cls_obj = models.ClassInfo.objects.filter(title='1年级1班')
cls_obj.teachers.create(name='张老师')

add

# 指派id为1的李老师到1年级1班
cls_obj = models.ClassInfo.objects.filter(title='1年级1班')
teacher_obj = models.Teachers.filter(id=1)
cls_obj.teachers.add(teacher_obj)  
# 也可以添加多个
teacher_list = models.Teachers.filter(id__in = [1, 2, 3, 4, 5])
cls_obj.teacher.add(*teacher_list)
# 也可以直接添加id
cls_obj.teacher.add(1)

Remove

# 从1年级1班中删除id为1的老师
cls_obj = models.ClassInfo.objects.filter(title='1年级1班')
cls_obj.teachers.remove(1)
# 或者删除对象
teacher_obj = models.Teachers.filter(id=1)
cls_obj.teachers.remove(teacher_obj)  

Query the teachers in Grade 1 and Class 1

cls_obj = models.ClassInfo.objects.filter(title='1年级1班')
teachers_list = cls_obj.teachers.all()

3. Aggregation and grouping

polymerization

The aggregation operation includes the following:
sum count avg max min

aggregate: Call this function to use aggregation. The return value is a dictionary. The
aggregation class needs to be imported before use, as shown in the following example

from django.db.models import Sum,Count,Max,Min,Avg
# 查看有多少学生
stu_count = models.Stuents.objects.all().aggregate(Count('id'))  

Grouping

Use annotate () for grouping

# 查询每个班级分配老师的数量
models.ClassInfo.objects.all().annotate(teacher_num=Count("teachers"))
Published 21 original articles · praised 0 · visits 315

Guess you like

Origin blog.csdn.net/qq_38756978/article/details/105302381