Skip to main content
 首页 » 编程设计

python之Django 动态访问相关属性

2025年05月04日40zengkefu

我正在使用 getattr 来动态访问模型的属性(假设 Student 模型有一个名为 name 的属性):

students = Student.objects.all() 
property = 'name' 
 
 
for student in students: 
    print getattr(student, property) 

这工作正常,但我想知道是否可以以相同的方式访问相关记录的属性,例如(假设每个学生都有一个相关组,其属性称为标题):

students = Student.objects.selected_related() 
property = 'group.title' 
 
 
for student in students: 
    print getattr(student, property) 

有了这个,我只得到错误“Student has no attribute group.title”

有什么办法可以实现吗?

感谢任何建议。

谢谢

请您参考如下方法:

虽然以下代码将执行您的要求:

students = Student.objects.all() 
attr_chain = "group.title".split(".") 
 
for student in students: 
    item = student 
    for attr in attr_chain: 
        item = getattr(item, attr) 
 
    print "%s is in the group %s" % (student, item) 

根据您的需要我建议您查看 Django 的 values_list 函数在 Queryset 类上,它在许多情况下可以缩短和简化代码。

name_attr = "name" 
 
#If you look in the documentation you will see why I use "__" here 
group_title_attr = "group__title"  
 
for student_name, group_title in Student.objects.all().values_list(name_attr, group_title_attr): 
    print "%s is in the group %s" % (student_name, group_title) 

相关文档是here和 here .