1、插入数据
- >>> from books.models import Publisher
- >>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
- ... city='Berkeley', state_province='CA', country='U.S.A.',
- ... website='http://www.apress.com/')
- >>> p1.save()
- >>> from books.models import Publisher
- >>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
- ... city='Berkeley', state_province='CA', country='U.S.A.',
- ... website='http://www.apress.com/')
- >>> p1.save()
2、查询
- >>> Publisher.objects.all()
- [<Publisher: Apress>, <Publisher: O'Reilly>]
- >>> Publisher.objects.all()
- [<Publisher: Apress>, <Publisher: O'Reilly>]
获取单个对象:
- >>> Publisher.objects.get(name="Apress")
- <Publisher: Apress>
- >>> Publisher.objects.get(name="Apress")
- <Publisher: Apress>
3、条件
筛选:
- >>> Publisher.objects.filter(name='Apress')
- [<Publisher: Apress>]
- >>> Publisher.objects.filter(name='Apress')
- [<Publisher: Apress>]
- >>> Publisher.objects.filter(name__contains="press")
- [<Publisher: Apress>]
- >>> Publisher.objects.filter(name__contains="press")
- [<Publisher: Apress>]
排序:
- >>> Publisher.objects.order_by("name")
- [<Publisher: Apress>, <Publisher: O'Reilly>]
- >>> Publisher.objects.order_by("name")
- [<Publisher: Apress>, <Publisher: O'Reilly>]
相当于 order by name asc
- >>> Publisher.objects.order_by("-name")
- >>> Publisher.objects.order_by("-name")
限制返回数据:
- >>> Publisher.objects.order_by('name')[0]
- <Publisher: Apress>
- >>> Publisher.objects.order_by('name')[0]
- <Publisher: Apress>
- >>> Publisher.objects.order_by('name')[0:2]
- >>> Publisher.objects.order_by('name')[0:2]
4、更新
- >>> Publisher.objects.filter(id=52).update(name='Apress Publishing')
- >>> Publisher.objects.filter(id=52).update(name='Apress Publishing')
- >>> p = Publisher.objects.get(name='Apress') #先查询
- >>> p.name = 'Apress Publishing' #更新
- >>> p.save() #保存
- >>> p = Publisher.objects.get(name='Apress') #先查询
- >>> p.name = 'Apress Publishing' #更新
- >>> p.save() #保存
5、删除
- >>> p = Publisher.objects.get(name="O'Reilly")
- >>> p.delete()
- >>> p = Publisher.objects.get(name="O'Reilly")
- >>> p.delete()
- >>> Publisher.objects.filter(country='USA').delete()
- >>> Publisher.objects.filter(country='USA').delete()