如何内省 django 模型字段?

发布于 2024-08-23 21:05:25 字数 254 浏览 3 评论 0原文

当我只知道字段名称和模型名称(都是纯字符串)时,我试图获取模型内字段的类信息。怎么可能呢?

我可以动态加载模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

以为你会在 2024-08-30 21:05:25

您可以使用模型的 _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.
    """

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'>

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.
    """
谈情不如逗狗 2024-08-30 21:05:25

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

已删除InDjango110警告:'get_field_by_name 是非官方 API
已被弃用。您也许可以将其替换为
'get_field()'

API 文档为 此处

The answer from Anurag Uniyal to use get_field_by_name is now (5 years later) outdated as get_field_by_name is deprecated.
Django will give you the following hint:

RemovedInDjango110Warning: 'get_field_by_name is an unofficial API
that has been deprecated. You may be able to replace it with
'get_field()'

API docs for get_field are here.

笛声青案梦长安 2024-08-30 21:05:25

如果您想查看 Django 模型对象上的所有字段,您可以通过在类(或实例化的模型对象)上调用 ._meta.get_fields() 来进行内省,以获取所有字段的列表。此 API 适用于最新版本的 Django。

示例:

from django.contrib.auth.models import User
User._meta.get_fields()

这将返回所有模型字段的元组。文档可以在 此处找到

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:

from django.contrib.auth.models import User
User._meta.get_fields()

This will return a tuple of all model fields. Documentation can be found HERE.

给我一枪 2024-08-30 21:05:25

django.db.models.loading.get_model() 已在 django 1.9 中删除。
你应该使用 django.apps 代替。

'get_field_by_name 是一个非官方 API,已在 Django 1.10 中弃用。您可以将其替换为“get_field()”

>>> from django.apps import apps
>>> from polls.models import Question
>>> QuestionModel = apps.get_model('polls','Question')
>>> QuestionModel._meta.get_field('pub_date')
>>> QuestionModel._meta.get_fields()
(<ManyToOneRel: polls.choice>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.CharField: question_text>, <django.db.models.fields.DateTimeField: pub_date>) 

问题链接

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()'

>>> from django.apps import apps
>>> from polls.models import Question
>>> QuestionModel = apps.get_model('polls','Question')
>>> QuestionModel._meta.get_field('pub_date')
>>> QuestionModel._meta.get_fields()
(<ManyToOneRel: polls.choice>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.CharField: question_text>, <django.db.models.fields.DateTimeField: pub_date>) 

link to issue

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文