繁体   English   中英

如何内省 django 模型字段?

[英]How to introspect django model fields?

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

我可以动态加载模型:

from django.db import models
model = models.get_model('myapp','mymodel')

现在我有字段 - 'myfield' - 我怎样才能获得该字段的类?

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

谢谢一堆!

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

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

RemovedInDjango110Warning: 'get_field_by_name 是一个已被弃用的非官方 API。 您可以将其替换为“get_field()”

get_field API 文档在这里

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

例子:

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

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

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

问题链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM