python - 如何自省(introspection) django 模型字段?

标签 python django-models introspection

当我只知道字段名称和模型名称(均为纯字符串)时,我正在尝试获取模型内字段的类信息。怎么可能?

我可以动态加载模型:

from django.db import models
model = models.get_model('myapp','mymodel')

现在我有字段 - 'myfield' - 我怎样才能获得该字段的类?

如果字段是关系型 - 如何获取相关字段?

非常感谢!

最佳答案

您可以使用模型的 _meta 属性来获取字段对象,并从字段中获取关系等等,例如考虑一个员工表,它有一个部门表的外键

In [1]: from django.db import models

In [2]: model = models.get_model('timeapp', 'Employee')

In [3]: dep_field = model._meta.get_field_by_name('department')

In [4]: dep_field[0].target_field
Out[4]: 'id'

In [5]: dep_field[0].related_model
Out[5]: <class 'timesite.timeapp.models.Department'>

来自 django/db/models/options.py

def get_field_by_name(self, name):
    """
    Returns the (field_object, model, direct, m2m), where field_object is
    the Field instance for the given name, model is the model containing
    this field (None for local fields), direct is True if the field exists
    on this model, and m2m is True for many-to-many relations. When
    'direct' is False, 'field_object' is the corresponding RelatedObject
    for this field (since the field doesn't have an instance associated
    with it).

    Uses a cache internally, so after the first access, this is very fast.
    """

关于python - 如何自省(introspection) django 模型字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2384436/

相关文章:

python - django自动创建的sqlite数据库在哪里?

ruby-on-rails - 从 Django 到 Rails,您如何持续使用 Rails 模型?

django - “SubfieldBase的处理方法已弃用。请改用Field.from_db_value。”

python - 我可以从 python 脚本中找到运行 python 脚本的可执行文件的路径吗?

python - 我尝试在Flask中使用Blueprints进行404错误处理,但似乎无法正常工作。这是我的代码:

python - 在 Python 3.4.1 中查找素数

python - 获取python中类的类路径或 namespace ,即使它是嵌套的

python - 获取创建的对象将被赋予的属性名称

python - 如何平滑和绘制 x 与 y 的加权平均值,由 x 加权?

python - 具有相同或相似字段的 Django 模型