首页 > 解决方案 > Python - 访问模型,其名称取决于变量值

问题描述

我正在尝试访问一个模型,其名称取决于变量值。

如果有一系列基于国家标识符的模型。例如学生_???在哪里 ???是国家标识符。

如果我想打印出每个国家/地区每个学生的详细信息,是否有一种方法可以循环遍历代码以动态访问每个模型。我可以通过 if 语句执行任务,但这需要将每个国家/地区代码硬编码到程序中,我想避免这种情况。

举个例子。我的views.py 看起来像:

mystudentcountry = {'AU', 'US', 'UK', 'EU'}

for country in mystudentcountry:

    mystudent = Student_AU.objects.all()

    for student in mystudent:
        print(f'{student.name} is {student.age} years old and studies in {country}')

在第三行代码“mystudent = Student_AU.objects.all()”中,是否可以用循环中标识的每个国家/地区替换“AU”。

谢谢您的支持。

标签: pythondjango

解决方案


将学生和国家/地区放入字典中,然后遍历字典项:

student_dict = {Student_AU: 'AU', Student_US: 'US', Student_UK: 'UK'}

for student, country in student_dict.items():
    mystudent = student.objects.all()
    for i in mystudent:
        print(f'{i.name} is {i.age} years old and studies in {country}')

这应该可以工作,除非Student_AU其他对象是可变的,例如列表。


推荐阅读