Discussion:
Using reflection with Django models to determine module containing the choices?
Stodge
2018-12-10 15:33:35 UTC
Permalink
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
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+***@googlegroups.com.
To post to this group, send email to django-***@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/78f7dcc2-c822-42cc-a06a-860ae080e5b8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Loading...