django数据库基本操作-增删改查(tip)-基本

时间:2025-03-12 13:37:31

补充:django外键保存

                #外键保存
form_data = Form_Data()
project, is_created = Project_Name.objects.get_or_create(name=select_text)
form_data.project = project

1、插入数据

 Python代码
>>> 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、查询

 Python代码
>>> Publisher.objects.all()
[<Publisher: Apress>, <Publisher: O'Reilly>]
 [python] view plain copy
>>> Publisher.objects.all()
[<Publisher: Apress>, <Publisher: O'Reilly>]

获取单个对象:

 Python代码
>>> Publisher.objects.get(name="Apress")
<Publisher: Apress>
 [python] view plain copy
>>> Publisher.objects.get(name="Apress")
<Publisher: Apress>

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

3、条件

筛选:

 Python代码
>>> Publisher.objects.filter(name='Apress')
[<Publisher: Apress>]
 >>> Publisher.objects.filter(name='Apress')
[<Publisher: Apress>]
 Python代码
>>> Publisher.objects.filter(name__contains="press")
[<Publisher: Apress>]
 [python] view plain copy
>>> Publisher.objects.filter(name__contains="press")
[<Publisher: Apress>]

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

排序:

 Python代码
>>> Publisher.objects.order_by("name")
[<Publisher: Apress>, <Publisher: O'Reilly>
 python] view plain copy
>>> Publisher.objects.order_by("name")
[<Publisher: Apress>, <Publisher: O'Reilly>]

相当于 order by name asc

 Python代码
>>> Publisher.objects.order_by("-name")
 [python] view plain copy
>>> Publisher.objects.order_by("-name")

加个负号相当于 order by name desc

限制返回数据:

 Python代码
>>> Publisher.objects.order_by('name')[0]
<Publisher: Apress>
 [python] view plain copy
>>> Publisher.objects.order_by('name')[0]
<Publisher: Apress>

相当于 limit 1

 Python代码
>>> Publisher.objects.order_by('name')[0:2]
 [python] view plain copy
>>> Publisher.objects.order_by('name')[0:2]

相当于 OFFSET 0 LIMIT 2

4、更新

 Python代码
>>> Publisher.objects.filter(id=52).update(name='Apress Publishing')
 [python] view plain copy
>>> Publisher.objects.filter(id=52).update(name='Apress Publishing')
 Python代码
>>> p = Publisher.objects.get(name='Apress') #先查询
>>> p.name = 'Apress Publishing' #更新
>>> p.save() #保存
 [python] view plain copy
>>> p = Publisher.objects.get(name='Apress') #先查询
>>> p.name = 'Apress Publishing' #更新
>>> p.save() #保存

5、删除

 Python代码
>>> p = Publisher.objects.get(name="O'Reilly")
>>> p.delete()
 [python] view plain copy
>>> p = Publisher.objects.get(name="O'Reilly")
>>> p.delete()
 Python代码
>>> Publisher.objects.filter(country='USA').delete()
 [python] view plain copy
>>> Publisher.objects.filter(country='USA').delete()