在Django模型中使用反射来确定包含选择的模块?

时间:2018-12-10 15:32:23

标签: django django-models reflection

假设我从Django文档中获取以下代码:

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = (
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
    )
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

但是我想做:

from student_app import choices
class Student(models.Model):
    year_in_school = models.CharField(
        max_length=2,
        choices=choices.YEAR_IN_SCHOOL_CHOICES,
        default=choices.FRESHMAN,
    )

总有没有使用反射来确定从哪个模块导入选择?

例如:

field = Student._meta.fields.get_field_by_name('year_in_school')
choices_source = some_clever_function(field)
print("Choices imported from '%s'" % choices_source)

我希望输出为:

  

从“ student_app”导入的选择。

显然,聪明的功能不存在,但希望能阐明我要做什么。

谢谢

0 个答案:

没有答案