django数据库基本操作增删改查

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()

2、查询

>>> Publisher.objects.all()
[<Publisher: Apress>, <Publisher: O'Reilly>]

获取单个对象:

>>> Publisher.objects.get(name="Apress")
<Publisher: Apress>
如果结果是多个对象或者没有返回结果则会抛出异常


3、条件

筛选:

>>> Publisher.objects.filter(name='Apress')
[<Publisher: Apress>]

>>> Publisher.objects.filter(name__contains="press")
[<Publisher: Apress>]
__contains部分会被Django翻译成 LIKE语句

排序:

>>> Publisher.objects.order_by("name")
[<Publisher: Apress>, <Publisher: O'Reilly>]

相当于 order by name asc

>>> Publisher.objects.order_by("-name")
加个负号相当于 order by name desc


限制返回数据:

>>> Publisher.objects.order_by('name')[0]
<Publisher: Apress>
相当于 limit 1

>>> Publisher.objects.order_by('name')[0:2]
相当于 OFFSET 0 LIMIT 2

4、更新

>>> Publisher.objects.filter(id=52).update(name='Apress Publishing')

>>> p = Publisher.objects.get(name='Apress') #先查询
>>> p.name = 'Apress Publishing' #更新
>>> p.save()  #保存

5、删除

>>> p = Publisher.objects.get(name="O'Reilly")
>>> p.delete()

>>> Publisher.objects.filter(country='USA').delete()






你可能感兴趣的:(数据库,django,import,website)