lundi 10 décembre 2018

Using reflection with Django models to determine module containing the choices?

Let's say I take the following code from the Django documentatation:

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,
    )

But instead I want to do:

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,
    )

Is there anyway using reflection to determine which module the choices are imported from?

For example:

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

I want the output to be:

Choices imported from 'student_app'.

Obviously the clever function does not exist but hopefully clarifies what I'm trying to do.

Thanks





Aucun commentaire:

Enregistrer un commentaire