如何反省django模型领域?

Evg*_*eny 35 python introspection django-models

我试图获取模型中的字段的类信息,当我只知道字段的名称和模型的名称(两个普通字符串).这怎么可能?

我可以动态加载模型:

from django.db import models
model = models.get_model('myapp','mymodel')
Run Code Online (Sandbox Code Playgroud)

现在我有场 - 'myfield' - 我怎么能得到那个领域的班级?

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

谢谢你!

Anu*_*yal 73

您可以使用模型的_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'>
Run Code Online (Sandbox Code Playgroud)

来自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.
    """
Run Code Online (Sandbox Code Playgroud)


tob*_*obs 7

Anurag Uniyal使用的答案get_field_by_name现在(5年后)已过时,因为get_field_by_name已弃用.Django会给你以下提示:

RemovedInDjango110Warning:'get_field_by_name是一个已弃用的非官方API.您可以用'get_field()'替换它

API文档就get_field这里.