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

1、插入数据


[python] view plain copy

>>> 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、查询


[python] view plain copy

>>> Publisher.objects.all()  

[<Publisher: Apress>, <Publisher: O'Reilly>]  

获取单个对象:


[python] view plain copy

>>> Publisher.objects.get(name="Apress")  

<Publisher: Apress>  

如果结果是多个对象或者没有返回结果则会抛出异常


3、条件


筛选:

[python] view plain copy

>>> Publisher.objects.filter(name='Apress')  

[<Publisher: Apress>]  


[python] view plain copy

>>> Publisher.objects.filter(name__contains="press")  

[<Publisher: Apress>]  

__contains部分会被Django翻译成LIKE语句

排序:


[python] view plain copy

>>> Publisher.objects.order_by("name")  

[<Publisher: Apress>, <Publisher: O'Reilly>]  

相当于 order by name asc

[python] view plain copy

>>> Publisher.objects.order_by("-name")  

加个负号相当于 order by name desc


限制返回数据:


[python] view plain copy

>>> Publisher.objects.order_by('name')[0]  

<Publisher: Apress>  

相当于 limit 1

[python] view plain copy

>>> Publisher.objects.order_by('name')[0:2]  

相当于 OFFSET 0 LIMIT 2


4、更新


[python] view plain copy

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


[python] view plain copy

>>> p = Publisher.objects.get(name='Apress') #先查询  

>>> p.name = 'Apress Publishing' #更新  

>>> p.save()  #保存  


5、删除

[python] view plain copy

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

>>> p.delete()  


[python] view plain copy

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


你可能感兴趣的:(mysql,python,django)