1、models.py
class Business(models.Model): prodline = models.CharField(max_length=32) code =models.CharField(max_length=32,null=True,blank=True) class Host(models.Model): nid = models.IntegerField(primary_key=True) hostname = models.CharField(max_length=32,blank=True,null=True,db_index=True) ip = models.GenericIPAddressField(blank=True,null=True,db_index=True) port = models.IntegerField(blank=True) prodline = models.ForeignKey(Business,to_field=‘id‘,on_delete=models.DO_NOTHING,null=True,blank=True)
2、数据
3、views.py
from django.shortcuts import render from models import * # Create your views here. def business(request): prodline1 = Business.objects.all() prodline2 = Business.objects.all().values(‘id‘,‘code‘) prodline3 = Business.objects.all().values_list(‘id‘,‘code‘) return render(request,‘business.html‘,{‘prodline1‘:prodline1,‘prodline2‘:prodline2,‘prodline3‘:prodline3})
分析:这里prodline1、prodline2、prodline3数据类型都是QuerySet,但内部数据是不同类型的。
prodline1内部是对象,prodline2内部是字段,prodline3内部是元组。
我们可以通过python manage.py shell 在命令行查看他们内部数据结构类型和数据结构
>>> from study.models import * >>> proline1 = Business.objects.all() >>> print type(proline1) <class ‘django.db.models.query.QuerySet‘> >>> prodline1 = Business.objects.all() >>> prodline1 [<Business: Business object>, <Business: Business object>, <Business: Business object>, <Business: Business object>] >>> prodline2 = Business.objects.all().values(‘id‘,‘code‘) >>> prodline2 [{‘code‘: u‘SPMS‘, ‘id‘: 1}, {‘code‘: u‘IPMS‘, ‘id‘: 2}, {‘code‘: u‘CPMS‘, ‘id‘: 3}, {‘code‘: u‘AMS‘, ‘id‘: 4}] >>> prodline3 = Business.objects.all().values_list(‘id‘,‘code‘) >>> prodline3 [(1, u‘SPMS‘), (2, u‘IPMS‘), (3, u‘CPMS‘), (4, u‘AMS‘)]
prodline1 获取到的是一个个对象组成的列表(也可以说是集合)。
prodline2 获取到的也是一个个字典组成的列表(也可以说是集合)。
proline3 获取到的是一个个元组组成的列表(也可以说是集合)。
templates模板中如何分别通过对象、字典、元组来循环取值?
business.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>业务线列表(对象)</h1> <ul> {% for row in prodline1 %} <li>{{ row.id }}-{{ row.code }}-{{ row.prodline }}</li> {% endfor %} </ul> <h1>业务线列表(字典)</h1> <ul> {% for row in prodline2 %} <li>{{ row.id }}-{{ row.code }}</li> {% endfor %} </ul> <h1>业务线列表(元组)</h1> <ul> {% for row in prodline3 %} <li>{{ row.0 }}-{{ row.1 }}</li> {% endfor %} </ul> </body> </html>
首先:模板语法取值都是使用“.“,对象和字典的取值方法一样,点后面接字段名,而元组则是使用索引来取值,索引从0开始。
时间: 2024-10-19 14:48:12