社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

render_to_response的第二个参数如何使用包含多个查询表结果的数组

江湖人小猫 • 10 年前 • 7854 次点击  

各位好,我最近新用Django写个页面,想要完成如下效果: 有三张表:

表1.table_name:

id | tablename

0 | student

1 | teacher

表2.student(内含学生信息)

表3.teacher(内含老师信息)

view.py原来如下:

def show(request):

  student=student.objects.filter(class="1")

  teacher=teacher.objects.filter(class="1")

  return render_to_response('show.html',{'student':student,'teacher':teacher})

现在想要做到想查的表添加到table_name表里即可,所以想写一个for循环,每次读取table_name的一行,再查询这行记录显示的表名。但render_to_response的第二个参数字典一定是写死的,不能根据for读取的结果随时改变,请问该怎么修改?

我的初步想法是把查询到的结果数组(诸如student、teacher)再塞进一个数组table_all,再写成:

return render_to_response('show.html',{'table_all':table_all})

但怎么做都无法成功。求各位大神指点。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/538
 
7854 次点击  
文章 [ 3 ]  |  最新文章 10 年前
Py站长
Reply   •   1 楼
Py站长    10 年前

@江湖人小猫

now_table.objects 你拿到是字符串啊,不是Class对象

江湖人小猫
Reply   •   2 楼
江湖人小猫    10 年前

@Django中国社区 谢谢回复。我已经基本完成数组的传递,但现在遇到一个新问题:

在views.py中

def show(request):
   ......
   tables=table.objects.all()   //读取table表中记录
   for one_table in tables:
        now_table=one_table .table_name   //把要使用的model名赋值给now_table
        now_table_content=now_table.objects.filter(class="1")
        all_tables.append(now_table_content)
   ......

运行时 now_table_content=now_table.objects.filter(class="1") 报错:

'unicode' object has no attribute 'objects'

请问怎样才能将表中查到的字段作为Model名进行查询,是否要转换为特定格式?谢谢!

Py站长
Reply   •   3 楼
Py站长    10 年前

return render_to_response('show.html',{'table_all':table_all})

这句话 中 table_all 变量中就是一个数组了,里面存储的是不同的数据结构(teacher , student)

你在template里读取时,需要注意,不同实例的属性是不一样的,很容易就会出错,

像你这种把不同数据放在一个数组的,最后就是 他们继承于同一个父类