Aagam Sheth
Aagam Sheth

Reputation: 691

Django Check is a Model Field has chocies defined or not

I have a model

class StudentEfficacy(models.Model):
    class FatherEducation(models.IntegerChoices):
        NoEducation = 0, _("No Education")
        PrimaryEducation = 1, _("Primary Education")
        SecondaryEducation = 2, _("Secondary Education")
        GraduateStudy = 3, _("Graduate Study")
        PostGraduateStudy = 4, _("Post Graduate Study")
        DoctorOfPhilosophy = 5, _("Doctor of Philosophy")

    student_efficacy_id = models.AutoField(primary_key=True)
    father_education = models.IntegerField(choices=FatherEducation.choices)
    study_time = models.IntegerField("Study Time in mins")

I want to dynamically check if the field has choices defined.

for example I want to do something like below:

stud = StudentEfficacy.objects.get(pk=1)
if stud.father_education has choices defined:
   print(stud.father_education)
elif not stud.study_time has choices defined:
   print(stud.study_time)  ​

Actually in the example above I have given fixed models and fields but actual use would be like below:

for model_inst in models_list:
    for field in model_field_list[model_inst._meta.verbose_name]
        if getattr(model_inst, field) has choices defined:
            print("Something")
        else:
            print("Something else")  ​

Upvotes: 0

Views: 286

Answers (2)

Aagam Sheth
Aagam Sheth

Reputation: 691

Just found a workaround form here : How to use getattr()

for model_inst in models_list:
    for field in model_field_list[model_inst._meta.verbose_name]
        if getattr(model_inst, f'get_{field}_display', False):
            print("Something")
        else:
            print("Something else")  

PS: Looking for better answers

EDIT 1:

definitely recommend this answer by Abdul Aziz Barkat

Upvotes: 0

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21807

You can get the fields definition from the _meta attribute of the model class. This attribute has the method get_field which will get the field for you. The field then would have the attribute choices which you can check:

from django.core.exceptions import FieldDoesNotExist


try:
    if model._meta.get_field(field).choices is not None:
        print("Something")
    else:
        print("Something else")
except FieldDoesNotExist:
    print("Non-existent field")

Upvotes: 2

Related Questions