Dan*_*Dan 2 python django getattr
我正在使用 getattr 像这样动态访问模型的属性(假设 Student 模型有一个名为 name 的属性):
students = Student.objects.all()
property = 'name'
for student in students:
print getattr(student, property)
Run Code Online (Sandbox Code Playgroud)
这工作正常,但是我想知道是否可以以相同的方式访问相关记录的属性,例如(假设每个学生都有一个相关组,其属性名为 title):
students = Student.objects.selected_related()
property = 'group.title'
for student in students:
print getattr(student, property)
Run Code Online (Sandbox Code Playgroud)
有了这个,我只是收到错误“学生没有属性 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)
Run Code Online (Sandbox Code Playgroud)
根据您的需要,我建议您查看values_listQueryset 类上的Django函数,它可以在许多情况下缩短和简化代码。
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1478 次 |
| 最近记录: |