python - 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")
解决方案
_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")
推荐阅读
- python - 解释sklearn.metrics.mean_absolute_error中`multioutput=[0.3, 0.7]`的底层处理
- python-3.x - 在 MacOS 10.15 上使用 Pip install 安装包
- python - git:在大型协作项目中重命名根文件夹而不会引起冲突
- webpack - Webpack 复制和订单优先级
- javascript - 有没有尺寸的css框架
- reactjs - 如何使用钩子从子组件重新渲染父组件?
- javascript - Promise 不适用于 Node.js 嵌套异步
- python - 试图从图像中移动像素
- opengl-es - 具有单个顶点/索引缓冲区的多个绘图调用?
- python-3.x - 如何使用 Flask-rest-jsonapi / JSON API 在同一个 POST 方法中创建对象和相关对象?