首页 > 解决方案 > Django Check 是一个模型字段是否定义了选择

问题描述

我有一个模型

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

我想动态检查该字段是否已choices定义。

例如我想做如下的事情:

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

实际上在上面的例子中,我给出了固定的模型和字段,但实际使用如下:

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")  ​

标签: pythondjangodjango-models

解决方案


_meta您可以从模型类的属性中获取字段定义。此属性具有get_field将为您获取字段的方法。然后该字段将具有choices您可以检查的属性:

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

推荐阅读