开启事务
def get(self, request, *args, **kwargs):
try:
with transaction.atomic():
self.modelHost.objects.create(hostname='db3',
groupid='1',
ip='10.0.0.2',
hostid='11256',
created_by=self.request.user.usernameor 'Admin')
self.modelDb.objects.create(dbname='db3',created_by=self.request.user.usernameor 'Admin')
host =self.modelHost.objects.filter(ip='10.0.0.2')
db =self.modelDb.objects.get(dbname='db3')
res = db.db_host.add(*host)
except Exception as e:
return HttpResponse(e)
return HttpResponse(str(res))
ORM 或
from django.db.modelsimport Q
def get(self,request,*args,**kwargs):
data = serializers.serialize("json",self.modelDb.objects.prefetch_related('db_host').filter(status=1))
filter_kwargs =dict()
filter_kwargs['status'] =1
# filter_kwargs['db_host__hostname__icontains'] = '10'
t = (Q(db_host__hostname__icontains='O') | Q(db_host__ip__icontains='10'), filter_kwargs)
aa =self.modelDb.objects.prefetch_related('db_host').filter(
(Q(db_host__hostname__icontains='O') | Q(db_host__ip__icontains='100')), **filter_kwargs)
return render_to_response('zabbix_host/db/test.html', {'db': aa})
多对多操作(接上面OR的数据)
{% for d in db%}
{% for h in d.db_host.all %}
{% endfor %}
{% endfor %}
Django Update
Update的时候不能使用get关键字
modelTs.objects.filter(pk=ots.id).update(total=4,used=7,free=9) #Yes
modelTs.objects.get(pk=ots.id).update(total=4,used=7,free=9) #No
POST表单复选框获取值
request.POST.getlist('xx')
ORM 不等于
model.User.objects.filter(~Q(name=xxx),id=111) #~Q()这个函数必须置前,否则会报错
TemplateView与DetailView不能同时被继承
class xxxView(LoginRequiredMixin, TemplateView, DetailView): # No
否则会出 'xxx' object has no attribute 'object'
因为TemplateView,与 DetailView下的get()冲突,get_object被改写
API注册
因为django框架下的api_urls.py文件中
router = BulkRouter() # this is why
路由注册
router.register(r'v1/Ts', api.TsViewSet,'ts')
TsViewSet 必须继承 BulkModelViewSet # this is result
TsViewSet(BulkModelViewSet)
假设注册其它路由继承基类 APIView
如下图
同样的在api_urls.py注册路由
url(r'^v1/ts-api', api.TsApi.as_view(),name='ts-api')
Template Tags
在应用下建立文件夹templatetags, #在common下py文件也可以添加新功能
在文件夹创建文件__init__.py
# -*- coding: utf-8 -*-
创建自己的模板标签文件,不能与已有的模板标签文件名重复
zabbix_host_tags.py
# -*- coding: utf-8 -*-
from collectionsimport defaultdict
from djangoimport template
register = template.Library()
@register.filter
def time_format(second):
day =int(second /86400)
hour =int((second - day *86400) /3600)
minute =int((second - day *86400 - hour *3600) /60)
return str(day) +'天, ' +str(hour) +'小时, ' +str(minute) +'分间'
在模板页xxx.html加载
{% load zabbix_host_tags %}
Queryset 查看执行语句
Modelname.objects.all().query
Queryset数据库字段为null判断
if column.value == None # 不能用 '' or null 与 php 不同