models对表的增删改查
1
|
models.Tb1.objects.create(c1
=
'xx'
, c2
=
'oo'
)
#增加一条数据
|
1
2
|
dic
=
{
'c1'
:
'xx'
,
'c2'
:
'oo'
}
models.Tb1.objects.creat(
*
*
dic) #可以接受字典类型数据 **kwargs
|
1
2
|
obj
=
models.Tb1(c1
=
'xx'
, c2
=
'oo'
)
obj.save()
|
1
|
models.Tb1.objects.get(
id
=
123
)
# 获取单条数据,不存在则报错(不建议使用)
|
1
|
models.Tb1.objects.
all
()
# 获取全部,它是一个Django的查询对象;取第一条.first();取列成字典.values('username');取列成列表.value_list()
|
1
|
models.Tb1.objects.
filter
(name
=
'seven'
)
# 获取指定条件的数据
|
1
|
models.Tb1.objects.
filter
(name
=
'seven'
).delete()
# 删除指定条件的数据
|
1
|
models.Tb1.objects.
filter
(name
=
'seven'
).update(gender
=
'0'
)
# 将指定条件的数据更新,均支持 **kwargs
|
1
2
3
|
obj
=
models.Tb1.objects.get(
id
=
1
)
obj.c1
=
'111'
obj.save()
# 修改单条数据,不常用
|
1
|
models.Tb1.objects.
filter
(name
=
'seven'
).count()
|
1
2
3
|
models.Tb1.objects.
filter
(id__gt
=
1
)
# 获取id大于1的值,(两个双下划线)
models.Tb1.objects.
filter
(id__lt
=
10
)
# 获取id小于10的值
models.Tb1.objects.
filter
(id__lt
=
10
, id__gt
=
1
)
# 获取id大于1 且 小于10的值
|
1
2
|
models.Tb1.objects.
filter
(id__in
=
[
11
,
22
,
33
])
# 获取id等于11、22、33的数据
models.Tb1.objects.exclude(id__in
=
[
11
,
22
,
33
])
# not in
|
1
2
3
|
models.Tb1.objects.
filter
(name__contains
=
"ven"
)
models.Tb1.objects.
filter
(name__icontains
=
"ven"
)
# icontains大小写不敏感
models.Tb1.objects.exclude(name__icontains
=
"ven"
)
|
1
|
models.Tb1.objects.filter(id__range=[
1
,
2
]) # 范围bettwen and
|
1
|
startswith,istartswith, endswith, iendswith,
|
1
2
|
models.Tb1.objects.
filter
(name
=
'seven'
).order_by(
'id'
)
# asc,从小到大排列
models.Tb1.objects.
filter
(name
=
'seven'
).order_by(
'-id'
)
# desc,从大到小排列
|
1
|
models.Tb1.objects.
all
()[
10
:
20
] #分页用
|
1
2
3
|
from django.db.models
import
Count, Min, Max, Sum #个数,最小,最大,求和
models.Tb1.objects.filter(c1=
1
).values(
'id'
).annotate(c=Count(
'num'
)) #annotate=grounp by,比如id为1的num列的个数
#
|
1
2
3
|
class
SimpleModel(models.Model):
username
=
models.CharField(max_length
=
64
)
password
=
models.CharField(max_length
=
64
)
|
1
2
3
4
5
|
def
index(request):
dic
=
{
"username"
:
"user1"
,
"password"
:
"123"
}
models.SimpleModel.objects.create(
*
*
dic)
obj
=
HomeForm.ImportForm(request.POST)
return
render(request,
'home/index.html'
,{
'obj'
:obj})
|
1
2
3
4
5
6
7
8
9
10
11
12
|
def
index(request):
ret
=
models.SimpleModel.objects.
all
()
print
ret
#[<SimpleModel: SimpleModel object>, ]对象的列表
print
type
(ret)
#<class 'django.db.models.query.QuerySet'>
print
ret.query
#SELECT "id", "username","password" FROM "app01_simplemodel"
print
models.SimpleModel.objects.
all
().values(
"username"
)
#[{'username': u'user1'}, {'username': u'user2'}, {'username': u'user3'}]
print
models.SimpleModel.objects.
all
().values_list(
"id"
,
"username"
)
#[(1, u'user1'), (2, u'user2'), (3, u'user3')]
#正是form--select的格式
obj
=
HomeForm.ImportForm(request.POST)
return
render(request,
'home/index.html'
,{
'obj'
:obj})
|