社区所有版块导航
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学习  »  问与答

[精华] Re:关于django一个有趣的问题

django • 10 年前 • 5758 次点击  

假如有两个表:teacher与student,他们的主键分别为属性id_t,id_s,其数据结构如下: Teacher(id_t,name_t,age_t,sex_t) Student(id_s,tid,name_s,age_s,sex_s):注、该表中的tid属性是外键,参照Teacher表的id_d属性。

我写了这样一条语句:set=Student.objects.select_related(‘Teacher__id_t’).filter(age_s=20)

问题: set中没有Teacher的name_t属性,请问如何才能得到该属性?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/626
 
5758 次点击  
文章 [ 6 ]  |  最新文章 10 年前
django
Reply   •   1 楼
django    10 年前

@Django中国社区 OK,Thank you! You are very great.

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

@django

print item.tid.name_t

django
Reply   •   3 楼
django    10 年前

@Django中国社区 这样查出来的是学生自己的姓名,而我想查的是该生对应老师的姓名。要得到这样的结果,有没有什么好的方法和建议,非常感谢!

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

@django print item.name_s

django
Reply   •   5 楼
django    10 年前

@Django中国社区 很高兴一早就收到你的热心帮助! 我试了下,出现这样的错误: 执行语句为:

set=Student.objects.select_related().filter(age_s=20) for item in set: ... print item.name_t ... 之后报错: Traceback (most recent call last): File "<console>", line 2, in <module> AttributeError: 'Student' object has no attribute 'name_t' 请问有什么好的办法可以得到?

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

set=Student.objects.select_related().filter(age=20)

你这样就拿到了studen集合了啊,每个studen都可以访问它的teacher

https://docs.djangoproject.com/en/1.4/ref/models/querysets/#django.db.models.query.QuerySet.select_related