9.Django数据查询

前面我们讲了model的属性和一些基本的创建与查询。这里专门来讲一下数据库接口相关的接口(QuerySet API)。

这节我们详细介绍一下数据库查询。

下面的教程基于:

from django.db import models

class News(models.Model):

     title = models.CharField(max_length=50)
     content = models.TextField()

     comment = models.CharField(max_length=100, null=True)
     views = models.IntegerField()
     pb_date = models.DateTimeField()

     def __str__(self):
         return '%s-%s' %(self.title, self.comment)

class Author(models.Model):
    name = models.CharField(max_length=20)
    email = models.EmailField()


    def __str__(self):
        return '%s:%s' % (self.name, self.email)

记得执行:

python3 manage.py makemigrations
python3 manage.py migrate

1.创建对象

进入Django的shell终端。

$ python3 manage.py shell

In [1]: from news.models import News, Author    
#创建对象方式1
In [2]: a = Author(name='admin', email='admin@qq.com')                               
In [3]: a.save()       
##创建对象方式2
In [4]: Author.objects.create(name='jack', email='jack@qq.com')                     
Out[4]: <Author: jack:jack@qq.com>
# #创建对象方式3
In [5]: t = Author()                                                                 
In [6]: t.name = 'tom'                                                               
In [7]: t.email='tom@qq.com'                                                         
In [8]: t.save()           
# #创建对象方式4, 返回元祖,如果没有返回true 数据库存在返回false
In [9]: Author.objects.get_or_create(name='sam', email='sam@qq.com')                 
Out[9]: (<Author: sam:sam@qq.com>, True)
In [10]:

2.查询数据

一下都可以写到python文件中,查询数据

In [10]: Author.objects.all()   #查询全部                                                    
Out[10]: <QuerySet [<Author: admin:admin@qq.com>, <Author: jack:jack@qq.com>, <Author: tom:tom@qq.com>, <Author: sam:sam@qq.com>]>
In [11]: Author.objects.all()[:2]     #查询全部 但切片只要2条数据                     
Out[11]: <QuerySet [<Author: admin:admin@qq.com>, <Author: jack:jack@qq.com>]>
In [12]: Author.objects.get(name='jack')# 根据name精确查询           
Out[12]: <Author: jack:jack@qq.com>
In [13]: Author.objects.filter()   #筛选,不传参跟all()一样                            
Out[13]: <QuerySet [<Author: admin:admin@qq.com>, <Author: jack:jack@qq.com>, <Author: tom:tom@qq.com>, <Author: sam:sam@qq.com>]>
In [14]: Author.objects.filter(name='sam') # 根据name过滤                            
Out[14]: <QuerySet [<Author: sam:sam@qq.com>]>
In [15]: Author.objects.filter(name__iexact='SAM')  #忽略大小写                       
Out[15]: <QuerySet [<Author: sam:sam@qq.com>]>
In [16]: Author.objects.filter(name__contains='j')  # 包含j的
Out[16]: <QuerySet [<Author: jack:jack@qq.com>]>
In [17]: Author.objects.filter(name__icontains='j') # 包含但是忽略大小写
Out[17]: <QuerySet [<Author: jack:jack@qq.com>]>
In [18]: Author.objects.filter(name__regex='^sam') # 正则匹配
In [20]: Author.objects.filter(name__iregex='^sAm') # 正则匹配 不区分大小写
Out[20]: <QuerySet [<Author: sam:sam@qq.com>]>
In [21]: Author.objects.exclude(name__contains='j') # 不包含
Out[21]: <QuerySet [<Author: admin:admin@qq.com>, <Author: tom:tom@qq.com>, <Author: sam:sam@qq.com>]>

3.删除

删除就是先查询到数据,然后调用delete().

# 查询然后删除
In [22]: Author.objects.get(name='jack').delete()                     
Out[22]: (1, {'news.Author': 1})

# 再次查询就没有jack了
In [23]: Author.objects.all()                                         
Out[23]: <QuerySet [<Author: admin:admin@qq.com>, <Author: tom:tom@qq.com>, <Author: sam:sam@qq.com>]>

4.更新

1.批量更新

In [27]:
Author.objects.filter(name='sam').update(name='sam',email='sam@163.com') # 过滤数据 会将所有的数据都更新
Out[27]: 1 # 影响的条数
## 再次查询,发现sam的邮箱已经更改了
In [28]: Author.objects.get(name='sam')                               
Out[28]: <Author: sam:sam@163.com>

2.单个更新

In [29]: a = Author.objects.get(name='sam') 
In [30]: a.email = 'sam@gmail.com' 
In [31]: a.save()

5.排序

作者按照名称排序

Author.objects.all().order_by('name')
Author.objects.all().order_by('-name') # 在 column name 前加一个负号,可以实现倒序

下一节

10.小项目实战

声明:原创文章,版权所有,转载请注明出处,https://litets.com。