開啟事務(wù)
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的數(shù)據(jù))
{% for d in db%}
<div>{{d.dbname }}</div>
{% for h in d.db_host.all %}
<div>{{h.ip }}</div>
{% endfor %}
{% endfor %}
Django Update
Update的時候不能使用get關(guān)鍵字
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表單復(fù)選框獲取值
request.POST.getlist('xx')
ORM 不等于
model.User.objects.filter(~Q(name=xxx),id=111) #~Q()這個函數(shù)必須置前篡石,否則會報錯
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)
假設(shè)注冊其它路由繼承基類 APIView
如下圖
同樣的在api_urls.py注冊路由
url(r'^v1/ts-api', api.TsApi.as_view(),name='ts-api')
Template Tags
在應(yīng)用下建立文件夾templatetags, #在common下py文件也可以添加新功能
在文件夾創(chuàng)建文件__init__.py
# -*- coding: utf-8 -*-
創(chuàng)建自己的模板標(biāo)簽文件,不能與已有的模板標(biāo)簽文件名重復(fù)
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 查看執(zhí)行語句
Modelname.objects.all().query
Queryset數(shù)據(jù)庫字段為null判斷
if column.value == None # 不能用 '' or null 與 php 不同