day20-django 跨表操作
一、引子
继承上一回的表结构
二、栗子
views
1 def host(request): 2 v1=models.Hostb.objects.filter(nid__gt=0) 3 for row in v1: 4 print(row.nid,row.hostname,row.ip,row.port,row.b.id,row.b.caption,row.b.code) 5 #print(row.b_id) 6 7 #数据库 host表中存放的 是 b_id, 查询的时候是一个对象,通过. 获取关联表的数据 8 9 return render(request,"host.html",{"v1":v1})
前端html
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <h1>主机列表</h1> <table border="1"> <thead> <tr> <th>主机id</th> <th>主机名</th> <th>ip</th> <th>端口</th> <th>业务线id</th> <th>业务线名称</th> <th>业务线code</th> </tr> </thead> <tbody> {% for row in v1 %} <tr> <td>{{ row.nid }}</td> <td>{{ row.hostname }}</td> <td>{{ row.ip }}</td> <td>{{ row.port }}</td> <td>{{ row.b_id }}</td> <td>{{ row.b.caption }}</td> <td>{{ row.b.code }}</td> </tr> {% endfor %} </tbody> </table> </body> </html>
urls
re_path("host/$",views.host),

三、总结及补充
如果有多个表做外键关联,可以通过 "." 一直关联下去,如果外键不指定,默认使用 id
1 class Foo(models.Model): 2 name=models.CharField(max_length=32) 3 4 class Business(models.Model): 5 #ID 6 caption=models.CharField(max_length=32) 7 code=models.CharField(max_length=32,null=True,default="sa") 8 fk=models.ForeignKey("Foo",on_delete=models.CASCADE) 9 #to_field="id" 默认跟表的主键做外键关联 10 11 class Hostb(models.Model): 12 nid=models.AutoField(primary_key=True) 13 hostname=models.CharField(max_length=32,db_index=True) 14 ip=models.GenericIPAddressField(protocol="ipv4",db_index=True) 15 port=models.IntegerField() 16 b=models.ForeignKey(to="Business",to_field="id",on_delete=models.CASCADE)
def host(request): v1=models.Hostb.objects.filter(nid__gt=0) for row in v1: # print(row.nid,row.hostname,row.ip,row.port,row.b.id,row.b.caption,row.b.code) #print(row.b_id) print(row.b.fk.name) #数据库 host表中存放的 是 b_id, 查询的时候是一个对象,通过. 获取关联表的数据 return render(request,"host.html",{"v1":v1})

浙公网安备 33010602011771号