簡體   English   中英

Django 檢查是 Model 字段是否定義了選擇

[英]Django Check is a Model Field has chocies defined or not

我有一個 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")

我想動態檢查該字段是否定義了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")  ​

您可以從 model class 的_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")

剛剛在這里找到了一種解決方法: 如何使用 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:尋找更好的答案

編輯1:

絕對推薦Abdul Aziz Barkat 的這個答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM