python - 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”。
谢谢您的支持。
解决方案
将学生和国家/地区放入字典中,然后遍历字典项:
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
其他对象是可变的,例如列表。
推荐阅读
- angular - Web api not binding correctly to html format in Angular
- java - 如何在添加到地图之前从收集器中的方法调用中过滤数据
- php - 在 centos 7 和使用 php 7 系统日志功能选项卡的日志记录为 ascii 十六进制代码 \x09
- c# - jQuery Disable buttons but not Click Event
- mysql - Checking existing record based on two fields
- c# - Firestore 复合索引排列爆炸?
- c# - 如何使用 EntityFramework Cores 错误影响 LINQ 选择决策
- selenium - 通过 eclipse 以空运行模式执行 TestNG.xml
- javascript - 通过单击 div 选择多选项
- objective-c - Removing non-ascii characters from NSData?