一、数据库操作
1、创建model表
基本结构
1
2
3
4
5
6
|
from
django.db
import
models
class
userinfo(models.Model):
#如果没有
models
.
AutoField,
默认会创建一个id的自增列
name
=
models.CharField(max_length
=
30
)
email
=
models.EmailField()
memo
=
models.TextField()
|
更多字段:
更多参数
2、注册APP,settings添加app
3、生成相应的表
python manage.py makemigrations
python manage.py migrate
4、admin后台注册表
python manage.py createsuperuser
创建用户
后台可以管理,添加数据
对数据进行增删改查
查
models.UserInfo.objects.all()
models.UserInfo.objects.all().values('user') #只取user列
models.UserInfo.objects.all().values_list('id','user') #取出id和user列,并生成一个列表
models.UserInfo.objects.get(id=1)
models.UserInfo.objects.get(user='yangmv')
成功获取数据
增
models.UserInfo.objects.create(user='yangmv',pwd='123456')
或者
obj =
models.UserInfo(user='yangmv',pwd='123456')
obj.save()
或者
dic = {'user':'yangmv','pwd':'123456'}
models.UserInfo.objects.create(**dic)
删
models.UserInfo.objects.filter(user='yangmv').delete()
改
models.UserInfo.objects.filter(user='yangmv').update(pwd='520')
或者
obj =
models.UserInfo.objects.get(user='yangmv')
obj.pwd = '520'
obj.save()
- 常用方法
二、常用字段
models.DateTimeField 日期类型 datetime
参数,
auto_now = True :则每次更新都会更新这个时间
auto_now_add 则只是第一次创建添加,之后的更新不再改变。
1
2
3
4
|
class
UserInfo(models.Model):
name
=
models.CharField(max_length
=
32
)
ctime
=
models.DateTimeField(auto_now
=
True
)
uptime
=
models.DateTimeField(auto_now_add
=
True
)
|
1
2
3
4
5
6
|
from
web
import
models
def
home(request):
models.UserInfo.objects.create(name
=
'yangmv'
)
after
=
models.UserInfo.objects.
all
()
print
after[
0
].ctime
return
render(request,
'home/home.html'
)
|
表结构的修改
表结构修改后,原来表中已存在的数据,就会出现结构混乱,
makemigrations更新表的时候就会出错
解决方法:
1、新增加的字段,设置允许为空。生成表的时候,之前数据新增加的字段就会为空。(null=True允许数据库中为空,blank=True允许admin后台中为空)
2、新增加的字段,设置一个默认值。生成表的时候,之前的数据新增加字段就会应用这个默认值
执行makemigrations,
migrate
后。老数据会自动应用新增加的规则
models.ImageField 图片
models.GenericIPAddressField IP
ip = models.GenericIPAddressField(protocol="ipv4",null=True,blank=True)
img = models.ImageField(null=True,blank=True,upload_to="upload")
数据库中保存的只是图片的路径
常用参数
选择下拉框 choices
class UserInfo(models.Model):
USER_TYPE_LIST = (
(1,'user'),
(2,'admin'),
)
user_type = models.IntegerField(choices=USER_TYPE_LIST,default=1)
2、连表结构
- 一对多:models.ForeignKey(其他表)
- 多对多:models.ManyToManyField(其他表)
- 一对一:models.OneToOneField(其他表)
应用场景:
- 一对多:当一张表中创建一行数据时,有一个单选的下拉框(可以被重复选择)
例如:创建用户信息时候,需要选择一个用户类型【普通用户】【金牌用户】【铂金用户】等。- 多对多:在某表中创建一行数据是,有一个可以多选的下拉框
例如:创建用户信息,需要为用户指定多个爱好- 一对一:在某表中创建一行数据时,有一个单选的下拉框(下拉框中的内容被用过一次就消失了
例如:原有含10列数据的一张表保存相关信息,经过一段时间之后,10列无法满足需求,需要为原来的表再添加5列数据
一对多:
1
2
3
4
5
6
|
class
Game(models.Model):
gname
=
models.CharField(max_length
=
32
)
class
Host(models.Model):
hostname
=
models.CharField(max_length
=
32
)
game
=
models.ForeignKey(
'Game'
)
|
这是Game表,里面有3个业务
这是主机表,可以通过外键,对应到Game表的业务的ID
多对多:
1
2
3
4
5
6
7
8
|
class
UserGroup(models.Model):
group_name
=
models.CharField(max_length
=
16
)
class
User(models.Model):
name
=
models.CharField(max_length
=
16
)
sex
=
models.CharField(max_length
=
16
)
email
=
models.EmailField(max_length
=
32
)
usergroup_user
=
models.ManyToManyField(
'UserGroup'
)
|
Django model会自动创建第3张关系表,用于对应user id 和usergroup id
这是UserGroup表
这是User表
这是Django自动生成的对应关系表
user_id = 1 为 yangmv,同时属于1,2(技术部,运营部)
一对一: (一对多增加了不能重复)
1
2
3
4
5
6
7
8
9
|
class
User2(models.Model):
name
=
models.CharField(max_length
=
16
)
sex
=
models.CharField(max_length
=
16
)
email
=
models.EmailField(max_length
=
32
)
class
Admin(models.Model):
username
=
models.CharField(max_length
=
32
)
password
=
models.CharField(max_length
=
32
)
admin_user2
=
models.OneToOneField(
'User2'
)
|
连接Mysql
一对多操作实例
首先生成2个表
1
2
3
4
5
6
7
8
|
from
django.db
import
models
class
Group2(models.Model):
caption
=
models.CharField(max_length
=
32
)
class
User2(models.Model):
username
=
models.CharField(max_length
=
32
)
group2
=
models.ForeignKey(
'Group2'
)
|
input和select标签用forms生成
先执行create_group生成3个group
已经查询出Group数据
添加
方法1,方法2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
def
create_user(request):
obj
=
Forign.UserForm(request.POST)
if
request.method
=
=
'POST'
:
if
obj.is_valid():
all_data
=
obj.clean()
#print all_data
#获取提交页面提交来的数据{'username': u'yang1', 'usergroup': 1}
#方法1,先获取对象,添加
#group_obj = models.Group2.objects.get(id=all_data['usergroup'])
#models.User2.objects.create(username=all_data['username'],usergroup=group_obj)
#方法2(推荐)
models.User2.objects.create(username
=
all_data[
'username'
],group2_id
=
all_data[
'usergroup'
])
#django会自动把数据库group2变为group2_id
else
:
error
=
obj.errors
print
error[
'username'
][
0
]
print
error[
'usergroup'
][
0
]
return
render(request,
'forign/create_user.html'
,{
'obj'
:obj})
|
方法3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
def
create_user(request):
obj
=
Forign.UserForm(request.POST)
if
request.method
=
=
'POST'
:
if
obj.is_valid():
all_data
=
obj.clean()
#print all_data
#获取提交页面提交来的数据{'username': u'yang1', 'usergroup': 1}
#方法1,先获取对象,添加
#group_obj = models.Group2.objects.get(id=all_data['usergroup'])
#models.User2.objects.create(username=all_data['username'],usergroup=group_obj)
#方法2(推荐)
#models.User2.objects.create(username=all_data['username'],group2_id=all_data['usergroup'])
#django会自动把数据库group2变为group2_id
#方法3(推荐)
models.User2.objects.create(
*
*
all_data)
print
models.User2.objects.
all
().count()
else
:
pass
# error = obj.errors
# print error['username'][0]
# print error['usergroup_id'][0]
return
render(request,
'forign/create_user.html'
,{
'obj'
:obj})
|
查询。展示出所有的数据
1
2
3
4
5
6
7
8
9
10
11
12
|
def
create_user(request):
obj
=
Forign.UserForm(request.POST)
if
request.method
=
=
'POST'
:
if
obj.is_valid():
all_data
=
obj.clean()
#方法3(推荐)
models.User2.objects.create(
*
*
all_data)
print
models.User2.objects.
all
().count()
else
:
pass
user_list
=
models.User2.objects.
all
()
return
render(request,
'forign/create_user.html'
,{
'obj'
:obj,
'user_list'
:user_list})
|
1
2
3
4
5
6
7
8
|
<
table
border="1">
{% for item in user_list %}
<
tr
>
<
td
>{{ item.username }}</
td
>
<
td
>{{ item.group2.caption }}</
td
>
</
tr
>
{% endfor %}
</
table
>
|
GET方式查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
def
create_user(request):
obj
=
Forign.UserForm(request.POST)
if
request.method
=
=
'POST'
:
if
obj.is_valid():
all_data
=
obj.clean()
#方法3(推荐)
models.User2.objects.create(
*
*
all_data)
print
models.User2.objects.
all
().count()
else
:
pass
#查用户
get_user
=
request.GET.get(
'username'
)
user_list
=
models.User2.objects.
filter
(username
=
get_user)
return
render(request,
'forign/create_user.html'
,{
'obj'
:obj,
'user_list'
:user_list})
|
1
2
3
|
#查组
get_val
=
request.GET.get(
'group'
)
user_list
=
models.User2.objects.
filter
(group2__caption
=
get_val)
|
一对多跨表操作,总结
1、group2对应的是一个对象
2、创建数据 group2_id ,直接查询数据库
3、获取数据,通过. group2.caption
4、查询数据,通过__ group2__caption
-------------------------------
SQL语句:
select distinct a.device_hash, sum(b.cmn_merge_count) from (select distinct device_hash from tbl_fileprotect_svc_instance where customer_id='3f500ac5-020d-3ce3-a2a2-51a59ddd606e') as a left join tbl_file_protect_alarm as b on a.device_hash = b.device_hash group by a.device_hash;
简化SQL如下(把子查询转化为WHERE语句):
select distinct a.device_hash, sum(b.cmn_merge_count) from tbl_fileprotect_svc_instance as a left join tbl_file_protect_alarm as b on a.device_hash = b.device_hash where a.customer_id='3f500ac5-020d-3ce3-a2a2-51a59ddd606e' group by a.device_hash;
select distinct a.device_hash, sum(b.cmn_merge_count) from tbl_fileprotect_svc_instance as a left join tbl_file_protect_alarm as b on a.device_hash = b.device_hash where a.customer_id='3f500ac5-020d-3ce3-a2a2-51a59ddd606e' group by a.device_hash;
select distinct a.device_hash, sum(b.cmn_merge_count) as alarm_sum from tbl_fileprotect_svc_instance as a left join tbl_file_protect_alarm as b on a.device_hash = b.device_hash where a.customer_id='3f500ac5-020d-3ce3-a2a2-51a59ddd606e' group by a.device_hash;
Django代码:
TODO:
方法一:
ret = [] device_list = models.FILE_PROTECT_INSTANCE.objects.filter(customer_id=customer_id) for item in device_list: tmp_dict = {} tmp_dict['device_hash'] = item.device_hash tmp_dict['hostname'] = item.hostname tmp_dict['status'] = item.status from django.db.models import Sum alarm_sum_group_items = models.FILE_PROTECT_ALARM.objects.filter(customer_id=customer_id).filter(device_hash=tmp_dict['device_hash']).values('device_hash').annotate(alarm_sum=Sum('cmn_merge_count')) #tmp_dict['customer_id'] = customer_id tmp_dict['alarm_sum'] = alarm_sum_group_items[0]['alarm_sum'] if (len(alarm_sum_group_items)!=0) else 0 ret.append(tmp_dict)
方法二: hashes = A.objects.values_list("device_hash", flat=True).filter(customer_id="3f500ac5-020d-3ce3-a2a2-51a59ddd606e") B.objects.filter(device_hash__in=hashes).values_list("device_hash").annotate(Sum("cmn_merge_count"))
SQL实现聚合查询统计(Sum,Count等)
from django.db.models import Sum #start_time = datetime.utcfromtimestamp(data['start_time']).replace(tzinfo=utc) #end_time = datetime.utcfromtimestamp(data['end_time']).replace(tzinfo=utc) end_time = datetime.now() start_time = end_time + timedelta(days=-1) condition['cmn_alert_time__range'] = (start_time, end_time) #alarm_sum_group_items_day = models.FILE_PROTECT_ALARM.objects.filter(**condition).values('customer_id').annotate(alarm_sum_day=Sum('cmn_merge_count')) alarm_sum_day = models.FILE_PROTECT_ALARM.objects.filter(**condition).aggregate(Sum("cmn_merge_count")) day_sum = alarm_sum_day['cmn_merge_count__sum'] if (alarm_sum_day['cmn_merge_count__sum'] is not None) else 0 end_time = datetime.now() start_time = end_time + timedelta(days=-7) condition['cmn_alert_time__range'] = (start_time, end_time) #alarm_sum_group_items_week = models.FILE_PROTECT_ALARM.objects.filter(**condition).values('customer_id').annotate(alarm_sum_week=Sum('cmn_merge_count')) alarm_sum_week = models.FILE_PROTECT_ALARM.objects.filter(**condition).aggregate(Sum("cmn_merge_count")) week_sum = alarm_sum_week['cmn_merge_count__sum'] if (alarm_sum_week['cmn_merge_count__sum'] is not None) else 0 condition = {} #condition['device_hash'] = data['device_hash'] condition['customer_id'] = customer_id end_time = datetime.now() #start_time = end_time + timedelta(days=-7) condition['cmn_alert_time__lte'] = end_time #alarm_sum_group_items_all = models.FILE_PROTECT_ALARM.objects.filter(**condition).values('customer_id').annotate(alarm_sum_all=Sum('cmn_merge_count')) alarm_sum_all = models.FILE_PROTECT_ALARM.objects.filter(**condition).aggregate(Sum("cmn_merge_count")) all_sum = alarm_sum_all['cmn_merge_count__sum'] if (alarm_sum_all['cmn_merge_count__sum'] is not None) else 0