Python的web框架Django的ORM数据库操作分析
1.建表
首先引用下,可model设定的各种字段类型
在model中建立一个表
from django.db import models
Create your models here.
class Person(models.Model):
#定义一个用户名字段,不能重复
username = models.CharField(max_length=10,unique=True)
password = models.CharField(max_length=10)
#默认值设定1
age = models.IntegerField()
#False 代表男 True 代表女 女为1 男为0
sex = models.BooleanField(default=False)
#可通过指定属性,来设定生成的列名,但在使用类中还是p_des
p_des = models.CharField(max_length=100,db_column='des')
create_date = models.DateTimeField(auto_now=True)
class Meta:
#指定生成表名,不指定默认生成格式为APP+类名
db_table = 'user'
python manage.py makemigrations
python manage.py migrate
通过代码随机生成些数据,这里有个小坑,也许会碰到=。=
def addUser(request):
for i in range(5):
person = Person()
num = random.randrange(100)
person.username = 'sola%d' % num
person.password = 'pass%d' % num
person.age = num
person.sex = num % 2
person.save()
return HttpResponse("success")
2.条件查询
可用过filter与exclude来链式查询。
def getUser(request):
#可以通过filter来查询(满足),可以继续链式多个条件。
#users = Person.objects.filter(usernamecontains="5").filter(usernamecontains=3)
#也可以用通过exclude(不满足),来查询
users = Person.objects.exclude(usernamecontains="5").filter(usernamecontains="9")
for user in users:
print(user.username)
print(user.create_date)
return HttpResponse("success")
3.另一种添加方法
def addUserTwo(request):
user = Person.objects.create(username='rui~',password='rui!',age=18)
user.save()
return HttpResponse("success")
4.排序
def getUser(request):
#直接加入order_by即可根据字段排序,默认是正序,前面加减号为倒叙
users = Person.objects.filter(agein=['73','34','84']).order_by("-username")
for user in users:
print(user.username)
print(user.create_date)
return HttpResponse("success")
5.将数据转成字典(转成Map)
def getUser(request):
#values可以直接把结果转换成字典,字典可通过工具直接转成JSON
users = Person.objects.filter(agein=['63','50','36','11']).values()
for user in users:
print(user.username)
print(user.create_date)
print(user.sex)
return HttpResponse("success")
6.二次查询(查询结果再次查询)
def getUser(request):
users = Person.objects.filter(age__in=['63','50','36','11'])
#可以再一次进行查询
users = users.filter(age='50')
for user in users:
print(user.username)
print(user.create_date)
print(user.sex)
return HttpResponse("success")
7.切片查询
def getUser(request):
#切片查询,从第四条开始,到第五条,不能有负数
users = Person.objects.all()[3:5]
for user in users:
print(user.username)
print(user.create_date)
print(user.sex)
return HttpResponse("success")
8.忽略大小写查询
查询前加入i即可
9.更改时间区域设定
默认Django有一套自定义的时区,与一般的数据库不匹配,会造成查询不准确,需要去setting中关闭它
#默认是True,改为False即可
USE_TZ = False
10.聚合函数
def getUser(request):
#聚合函数,Avg平均,Count数量,Max最大,Min最小,Sum求和;参数填入字段
avgNum = Person.objects.aggregate(Avg("age"))
print(avgNum)
return HttpResponse("success")
11.某一条字段进行对比
def getUser(request):
#一条数据中某字段进行对比,可进行大小等于,包含等
#users = Person.objects.filter(age=F("id"))
#也可以这么写,age 大于 id+1
users = Person.objects.filter(agegt=F("id")+1)
function(){ //点值计算器http://www.fx61.com/dotpoint.html
print(users.values())
return HttpResponse("success")
12.逻辑运算符的查询写法
def getUser(request):
users = Person.objects.filter(Q(agegt=90) & Q(age__lt=100))
print(users.values())
return HttpResponse("success")
13.封装某些默认查询条件
因为查询方法是通过Django在model中自动生成查询objectsManager,我们可以建立一个类继承于Manager,并重写他的查询方法,再给Model类中赋予对象给objects参数,再通过调用objects参数进行查询,就会过滤想默认过滤的条件。
model
#歌曲类管理
class SongManager(models.Manager):
def get_queryset(self):
return super(SongManager,self).get_queryset().filter(is_deleter=1)
#继承歌曲管理类
class Song(models.Model):
name = models.CharField(max_length=50)
length = models.CharField(max_length=10)is_deleter = models.IntegerField(max_length=1,default=0)singer = models.CharField(max_length=30) objects = SongManager()
views
def getSong(request):
songs = Song.objects.all()
for song in songs:
print(song.name)
return HttpResponse("success")
原文链接:blog.csdn.net/jiulanhao/article/details/103027355