增加记录的两种方式:
Vocation.objects.create(name="奥里给", age=29)new_vocation = Vocation(name="奥里给", age=29)new_vocation.save()
删除记录:
Vocation.objects.filter(id=1).delete()
修改记录:
Vocation.objects.filter(id=1).update(name="zhangsan")new_voc = Vocation.objects.get(id=1)new_voc.name = "laowang"new_voc.age = 26new_voc.save()
获取记录:
Vocation.objects.filter.all()Vocation.objects.filter(id=1)Vocation.objects.get(id=1)Vocation.objects.filter(id__in=[1, 2, 3])Vocation.objects.exclude(id__in=[2, 3])# 查询1<id<5的记录Vocation.objects.filter(id__gt=1, id__lt=5)Vocation.objects.order_by("name") #按name正序Vocation.objects.order_by("-name") #按name倒序Vocation.objects.distinct() #去重
objects.all()、objects.values()、objects.values_list()区别:
d1 = Department.objects.all()d2 = Department.objects.values()d3 = Department.objects.values_list()d4 = Department.objects.values_list("title")print(d1) --><QuerySet [<Department: Department object (2)>, <Department: Department object (1)>]> #(all())print(d2) --><QuerySet [{'id': 2, 'title': 'C++'}, {'id': 1, 'title': 'java'}]> #(values())print(d3) --><QuerySet [(2, 'C++'), (1, 'java')]> #(values_list())print(d4)--><QuerySet [('C++',), ('java',)]>
all()返回对象序列
values()返回字典类型序列
values_list()返回元组类型序列
返回值为QuerySet的函数不会立即去数据库操作数据,只有当需要使用QuerySet里面的值时才回去数据库中获取数据。
查询单条记录:
Vocation.objects.get(id=1)Vocation.objects.filter(id=1).first()Vocation.objects.last()Vocation.objects.count()
