新建对象
1.save
>>> a = Person(name='name1', age=1)
>>> a.save()
2.create
>>> a = Person.objects.create(name='name4', age=4)
3.get_or_create
>>> Person.objects.get_or_create(name='name1', age=1)
(<Person: name1>, False) # 已存在
>>> Person.objects.get_or_create(name='name10', age=1)
(<Person: name10>, True) # 不存在,插入
查询对象
1.
>>> Person.objects.all() # 所有记录
[<Person: name1>, <Person: name2>, <Person: name3>, <Person: name4>, <Person: name5>, <Person: name6>, <Person: name6>]
2.get
>>> Person.objects.get(name='name1') # 结果多于一条、不存在,都会报错。
<Person: name1>
3.filter
>>> Person.objects.filter(name='name6')
[<Person: name6>, <Person: name6>]
>>> Person.objects.filter(name='name6')[0].age
4
>>> Person.objects.filter(name='name6')[1].age
6
>>> Person.objects.filter(name='name6', age=4) # 没有时,为空。
[<Person: name6>]
4.exclude
>>> Person.objects.exclude(name='name6')
[<Person: name1>, <Person: name2>, <Person: name3>, <Person: name4>, <Person: name5>]
删除:
>>> a = Person.objects.filter(name='name6')
>>> a
[<Person: name6>, <Person: name6>]
>>> a.delete()
删除所有:
Person.objects.all().delete()
修改:
1.update
>>> a = Person.objects.filter(name='name6').update(num=23)
2.obj.field
>>> a = Person.objects.filter(name='name6', num=24)[0]
>>> a.num = 23
>>> a.save()