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

88 views
Skip to first unread message

Stodge

unread,
Dec 10, 2018, 10:33:35 AM12/10/18
to Django users
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

Simon Charette

unread,
Dec 10, 2018, 11:56:53 AM12/10/18
to Django users
Given choices are defined at the module level I guess you could
iterate over objects defined in each `sys.modules` (or the ones
likely to define choices) and use the `is` operator to compare all
of them to the field choices.

This will perform badly and shouldn't be used for anything else
than one off debugging reflection though.

Best,
Simon

Stodge

unread,
Dec 10, 2018, 10:32:07 PM12/10/18
to Django users
Thanks Simon. It's for an offline tool so high performance isn't the top priority.
Reply all
Reply to author
Forward
0 new messages