python【第二十篇】Django表的多对多、Ajax

时间:2021-06-23 21:40:14

1 创建多对多表的方式有两种

1.1 方式一:自定义关系表

 class Host(models.Model):
nid = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=32,db_index=True)
ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to="Business", to_field='id') class Application(models.Model):
name = models.CharField(max_length=32) class HostToApp(models.Model):
hobj = models.ForeignKey(to='Host',to_field='nid')
aobj = models.ForeignKey(to='Application',to_field='id')

那么我们可以通过对第三张表的操作HostToApp,增删改查各种多对多的关系:

models.HostToApp.objects.create(hobj_id=1,aobj_id=2)

1.2 方式二:自动创建第三张表

 class Host(models.Model):
nid = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=32,db_index=True)
ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to="Business", to_field='id') class Application(models.Model):
name = models.CharField(max_length=32)
r = models.ManyToManyField("Host")

这种方式无法直接操作第三张表,但是可以通过10行r这个对象,进行间接操作第三张表:

obj = models.Application.objects.get(id=1)
obj.name # 第三张表操作
# 添加
obj.r.add(1)
obj.r.add(2)
obj.r.add(2,3,4)
obj.r.add(*[1,2,3,4]) # 删除
obj.r.remove(1)
obj.r.remove(2,4)
obj.r.remove(*[1,2,3]) # 清除obj所对应的所有主机
obj.r.clear() # 设置,可以理解为删除原来的,设置成下面的
obj.r.set([3,5,7]) # 所有相关的主机对象“列表” QuerySet
obj.r.all()

2 Ajax

为某个标签写个AJAX请求:

JS代码:

 $('#app-edit5').click(function () {
$.ajax({
url: "/cmdb/app_edit_ajax/", //提交给哪个url
type: "POST", //请求方式
data: $('#app-edit-form').serialize(), //请求数据可以以字典的形式,此处是获取这个form表单中的所有
traditional: true, // 提交数据中有数组
dataType: "JSON", // 写了这个不用反序列化data,data就直接是对象
success:function (data) {
if(data.status){
location.reload(); //刷新页面
}else {
$('#app_edit_error').text(data.error);
}
}
})
});

后端代码:

 def app_edit_ajax(request):
if request.method == "POST":
ret = {'status': True, 'error': None, 'data': None}
aid = request.POST.get("nid")
app_name = request.POST.get("app-name")
h_list = request.POST.getlist("app-hosts")
try:
if app_name:
obj = models.Application.objects.filter(id=aid).first()
obj.name = app_name
obj.save()
obj.r.set(h_list)
else:
ret['status'] = False
ret['error'] = "应用名称不能为空"
except Exception as e:
print("错误信息:", e)
ret['status'] = False
ret['error'] = '请求错误' return HttpResponse(json.dumps(ret))

3 Django总结

3.1 完整的Django的请求周期:

 请求 -> 路由系统 -> 试图函数(获取模板+数据=》渲染) -> 字符串返回给用户

3.2 路由系统书写的几种方式

 /index/                ->  函数或类.as_view()
/detail/(\d+) -> 函数(参数) 或 类.as_view()(参数)
/detail/(?P<nid>\d+) -> 函数(参数) 或 类.as_view()(参数) /detail/ -> include("app01.urls")
/detail/ name='a1' -> include("app01.urls")
- 视图中:reverse
- 模板中:{% url "a1" %}

3.3 视图函数

FBV

from django.views import View
class Home(View):
def dispatch(self, request, *args, **kwargs):
print("before")
result = super(Home, self).dispatch(request, *args, **kwargs)
print("after")
return result def get(self, request):
print(request.method)
return render(request, "home.html") def post(self, request):
print(request.method, "post")
return render(request, "home.html")

CBV:

def host(request):
if request.method == "GET":
h_dic = models.Host.objects.all()
h_dic1 = models.Host.objects.filter(nid__gt=0).values('nid', 'hostname', 'b_id', 'b__caption')
h_dic2 = models.Host.objects.filter(nid__gt=0).values_list('nid', 'hostname', 'b_id', 'b__caption') b_list = models.Business.objects.all() return render(request, "host.html", {'h_dic': h_dic, 'h_dic1': h_dic1, 'h_dic2': h_dic2, 'b_list': b_list}) elif request.method == "POST":
h = request.POST.get("hostname", None)
i = request.POST.get("ip", None)
p = request.POST.get("port", None)
b = request.POST.get("b_id", None) models.Host.objects.create(hostname=h,
ip=i,
port=p,
b_id=b) return redirect('/host/')

获取用户请求中的数据:

 request.POST.get
request.GET.get
reqeust.FILES.get() #获取文件 # checkbox,
........getlist() #获取列表 request.path_info # 获取路径 文件对象 = reqeust.FILES.get()
文件对象.name
文件对象.size
文件对象.chunks()
#依赖这个设置 <form enctype="multipart/form-data"></form>

给用户返回数据:

render(request, "模板的文件的路径", {'k1': [1,2,3,4],"k2": {'name': 'zingp','age': 73}})
redirect("URL")
HttpResponse(字符串)

3.4 模板语言

# 视图函数中:
render(request, "模板的文件的路径", {'obj': 1234, 'k1': [1,2,3,4],"k2": {'name': 'zingp','age': 73}}) #html
<html> <body>
<h1> {{ obj }} </h1>
<h1> {{ k1.3 }} </h1>
<h1> {{ k2.name }} </h1>
{% for i in k1 %}
<p> {{ i }} </p>
{% endfor %} {% for row in k2.keys %}
{{ row }}
{% endfor %} {% for row in k2.values %}
{{ row }}
{% endfor %} {% for k,v in k2.items %}
{{ k }} - {{v}}
{% endfor %} </body>
</html>