gpt4 book ai didi

python - Django 动态访问相关属性?

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:27 25 4
gpt4 key购买 nike

我正在使用 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)

相关文档是herehere .

关于python - Django 动态访问相关属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8751450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com