Python-访问一个模型,其名称取决于变量值



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

如果有一系列基于国家标识符的型号。例如Student_???哪里是国家/地区标识符。

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

举个例子。我的视图.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";每个国家都在循环中标识。

感谢您的支持。

实现这一点的一种方法是使用getattr,但它可能需要在模型中进行一些组织。

如果您有一个名为models的文件夹,并且在该文件夹中有students_au.pystudents_us.py。。。,您可以创建一个具有以下的__init__.py文件

from students_au import students_AU # imports the actual model frm the file
from students_us import students_US
from students_uk import students_UK

然后在您的views.py

import models
mystudentcountry = {'AU', 'US', 'UK', 'EU'}
for country in mystudentcountry:
# this is the magic
# getattr(obj, "name_of_attribute") is the same as obj.name_of_attribute
country_model = getattr(models, "students_%s" % country) 
mystudent = country_model.objects.all()
for student in mystudent:
print(f'{student.name} is {student.age} years old and studies in {country}')

将学生和国家放入字典,然后迭代字典项:

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和其他对象(例如列表(是可变的,否则这应该有效。

如果是静态国家列表,则可以创建自定义管理器。

https://docs.djangoproject.com/en/3.1/topics/db/managers/

示例:

class StudentsFromAU(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(country='AU')
class Book(models.Model):
# your model description
objects = models.Manager() # The default manager.
au_students = DahlBookManager() # The specific manager.

现在你可以得到它们像:

Student.au_students.all()

最新更新