如何内省 django 模型字段?
当我只知道字段名称和模型名称(都是纯字符串)时,我试图获取模型内字段的类信息。怎么可能呢?
我可以动态加载模型:
from django.db import models
model = models.get_model('myapp','mymodel')
现在我有字段 - 'myfield' - 如何获取该字段的类?
如果字段是关系字段 - 如何获取相关字段?
非常感谢!
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?
I can load the model dynamically:
from django.db import models
model = models.get_model('myapp','mymodel')
Now I have field - 'myfield' - how can I get the class of that field?
If the field is relational - how to get related field?
Thanks a bunch!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用模型的 _meta 属性来获取字段对象,并且从字段中您可以获取关系等等,例如考虑一个员工表,该表具有
来自 django/db/models/options 的部门表的外键。 py
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 tablefrom django/db/models/options.py
Anurag Uniyal 使用
get_field_by_name
的答案现在(5 年后)已经过时,因为get_field_by_name
已被弃用。Django 会给你以下提示:
API 文档为 此处。
The answer from Anurag Uniyal to use
get_field_by_name
is now (5 years later) outdated asget_field_by_name
is deprecated.Django will give you the following hint:
API docs for
get_field
are here.如果您想查看 Django 模型对象上的所有字段,您可以通过在类(或实例化的模型对象)上调用
._meta.get_fields()
来进行内省,以获取所有字段的列表。此 API 适用于最新版本的 Django。示例:
这将返回所有模型字段的元组。文档可以在 此处找到。
If you would like to see ALL fields on a Django model object you can simply introspect it by calling
._meta.get_fields()
on the class (or an instantiated model object) to get at list of all fields. This API is current with the latest version of Django.Example:
This will return a tuple of all model fields. Documentation can be found HERE.
django.db.models.loading.get_model() 已在 django 1.9 中删除。
你应该使用 django.apps 代替。
'get_field_by_name 是一个非官方 API,已在 Django 1.10 中弃用。您可以将其替换为“get_field()”
问题链接
django.db.models.loading.get_model() has been removed in django 1.9.
You are supposed to use django.apps instead.
'get_field_by_name is an unofficial API that has been deprecated in Django 1.10. You may be able to replace it with 'get_field()'
link to issue