一,用于跨表操作
只要是object后面字符串都是用双下划线__。其它地方用点.
如:的values中的group_code__name.group_code是一个外键
def list(request):
host = models.host.objects.filter(id__gt=3).values('ip','port','group_code_id','group_code__name')
for i in host:
print(i['group_code__name'],i['group_code_id'])
return render(request,'list.html',{'host':host,})
二,3种外键查询
veiws:
def list(request):
v1 = models.host.objects.filter(id__gt=3)
for i in v1:
print(i.ip,i.port,i.group_code_id,i.group_code.name)
v2 = models.host.objects.filter(id__gt=3).values('ip','port','group_code_id','group_code__name')
for i in v2:
print(i['ip'],i['port'],i['group_code__name'],i['group_code_id'])
v3 = models.host.objects.filter(id__gt=3).values_list('ip','port','group_code_id','group_code__name')
for i in v3:
print(i[0],i[1],i[2],i[3])
return render(request,'list.html',{'v1':v1,'v2':v2,'v3':v3}) html:
<h1>对象获取:</h1>
<table border="1">
<thead><td>ip</td><td>port</td><td>group_id</td><td>group_name</td></thead>
{% for i in v1 %}
<tr><td>{{ i.ip}}</td><td>{{ i.port}}</td><td>{{ i.group_code_id}}</td><td>{{ i.group_code.name}}</td></tr>
{% endfor %}
</table>
<h1>字典获取:</h1>
<table border="1">
<thead><td>ip</td><td>port</td><td>group_id</td><td>group_name</td></thead>
{% for i in v2 %}
<tr><td>{{ i.ip}}</td><td>{{ i.port}}</td><td>{{ i.group_code_id}}</td><td>{{ i.group_code__name}}</td></tr>
{% endfor %}
</table>
<h1>元组获取:</h1>
<table border="1">
<thead><td>ip</td><td>port</td><td>group_id</td><td>group_name</td></thead>
{% for i in v3 %}
<tr><td>{{ i.0}}</td><td>{{ i.1}}</td><td>{{ i.2}}</td><td>{{ i.3}}</td></tr>
{% endfor %}
</table>
。。