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.
"""
您可以使用模型的
_meta
属性来获取field对象,而从field中您可以获取关系以及更多信息,例如,考虑一个employee表,该表具有department表的外键来自django/db/models/options.py
如果您想查看Django模型对象上的所有字段,可以通过调用类(或实例化的模型对象)上的
._meta.get_fields()
来获得所有字段的列表,从而简单地对其进行内省。这个API是Django的最新版本。示例:
这将返回所有模型字段的元组。文档可以找到HERE。
Anurag Uniyal使用
get_field_by_name
的答案现在(5年后)已经过时,因为get_field_by_name
已被弃用。 Django会给你以下提示:get_field
的API文档是here。相关问题 更多 >
编程相关推荐