python【第二十篇】Django表的多对多、Ajax
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>
python【第二十篇】Django表的多对多、Ajax的更多相关文章
- Python开发【第二十篇】:缓存
Python开发[第二十篇]:缓存redis&Memcache 点击这里 Python之路[第九篇]:Python操作 RabbitMQ.Redis.Memcache.SQLAlchemy ...
- Python之路【第二十篇】:待更新中.....
Python之路[第二十篇]:待更新中.....
- Python第二十六天 python装饰器
Python第二十六天 python装饰器 装饰器Python 2.4 开始提供了装饰器( decorator ),装饰器作为修改函数的一种便捷方式,为工程师编写程序提供了便利性和灵活性装饰器本质上就 ...
- Python第二十四天 binascii模块
Python第二十四天 binascii模块 binascii用来进行进制和字符串之间的转换 import binascii s = 'abcde' h = binascii.b2a_hex(s) # ...
- python第二十九课——文件读写(复制文件)
自定义函数:实现文件复制操作有形参(2个) 没有返回值相似版(不用) def copyFile(src,dest): #1.打开两个文件:1个关联读操作,1个关联写操作 fr=open(src,'rb ...
- python第二十九课——文件读写(读取读取中文字符)
演示:读取中文字符 结论: 1).如果不设置encoding,默认使用gbk进行编解码 2).如果编码和解码不一致,最终导致报错,但是一旦设置了errors='ingore',那么就不会报错,而采取乱 ...
- 孤荷凌寒自学python第二十九天python的datetime.time模块
孤荷凌寒自学python第二十九天python的datetime.time模块 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) datetime.time模块是专门用来表示纯时间部分的类. ...
- 孤荷凌寒自学python第二十六天python的time模块的相关方法
孤荷凌寒自学python第二十六天python的time模块的相关方法 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 要使用time模块的相关方法,必须在文件顶端引用: import tim ...
- 孤荷凌寒自学python第二十五天初识python的time模块
孤荷凌寒自学python第二十五天python的time模块 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 通过对time模块添加引用,就可以使用python的time模块来进行相关的时间操 ...
- 孤荷凌寒自学python第二十四天python类中隐藏的私有方法探秘
孤荷凌寒自学python第二十四天python类中隐藏的私有方法探秘 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天发现了python的类中隐藏着一些特殊的私有方法. 这些私有方法不管我 ...
随机推荐
- POJ 2553 The Bottom of a Graph TarJan算法题解
本题分两步: 1 使用Tarjan算法求全部最大子强连通图.而且标志出来 2 然后遍历这些节点看是否有出射的边,没有的顶点所在的子强连通图的全部点,都是解集. Tarjan算法就是模板算法了. 这里使 ...
- javascript Deferred和递归次数限制
function runAsyncTTS(text,speecher,audiopath) { var def = jQuery.Deferred(); var args = {"Synth ...
- [Javascript] The Array forEach method
Most JavaScript developers are familiar with the for loop. One of the most common uses of the for lo ...
- C# - 系统类 - Math类
Math类 ns:System 此类除了提供了最基本的运算功能 还提供了三角.指数.超常的计算 它的所有方法都是静态的 Math类的字段 E 常量e 自然对数底 值为2.71828182845905 ...
- struts2+ajax
web网页开发中需要用到struts2来处理action,通过struts2定义后端java类. <action name="loginAction" class=" ...
- 练习题之ThreadLocal
public class ThreadLocalMain { private static ThreadLocal<Integer> value = new ThreadLocal< ...
- Atom编辑器入门到精通(三) 文本编辑基础
身为编辑器,文本编辑的功能自然是放在第一位的,此节将总结常用的文本编辑的方法和技巧,掌握这些技巧以后可以极大地提高文本编辑的效率 注意此节中用到的快捷键是Mac下的,如果你用的系统是Win或者Linu ...
- 百思不得其解—这些年做Web开发遇到的坑?
请教一个问题:Bootstrap 模态框modal里面的嵌入 iframe ,然后iframe 里面载入的是优酷的视频 ,现在的问题是:这个模态框在谷歌浏览器上面可以播放出视频,而在ff浏览器里面无 ...
- 在jsp中的css
div#one{}div#two{ width:auto; height:20px;background-color:#FAEBD7;text-align:right;}div#three{ widt ...
- VS2013+SVN管理
进入新公司,大部分员工使用的是VS2013 ,所以搜集了下支持VS2013的一些SVN工具,现在发布到园子,供大家使用. CodeMaid插件,能够很好的格式化代码,强迫症的最爱: TortoiseS ...