问题描述
当我只知道字段的名称和模型的名称(都是纯字符串)时,我试图获取有关模型内字段的类信息.怎么可能?
I am trying to obtain class information on a field inside a model, when I only know name of the field and name of the model (both plain strings). How is it possible?
我可以动态加载模型:
from django.db import models
model = models.get_model('myapp','mymodel')
现在我有了字段 - 'myfield' - 我怎样才能得到那个字段的类?
Now I have field - 'myfield' - how can I get the class of that field?
如果字段是相关的 - 如何获取相关字段?
If the field is relational - how to get related field?
非常感谢!
推荐答案
您可以使用模型的 _meta
属性来获取字段对象,并从字段中获取关系等等.考虑一个员工表,它有一个部门表的外键
You can use model's _meta
attribute to get field object and from field you can get relationship and much more e.g. consider a employee table which has a foreign key to a department table
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
from 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.
"""
这篇关于如何内省 django 模型字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!