如何检查django模型字段?

37 投票
4 回答
23195 浏览
提问于 2025-04-15 20:02

我想获取一个模型里面某个字段的类信息,但我只知道这个字段的名字和模型的名字(都是普通的字符串)。请问这怎么实现呢?

我可以动态加载这个模型:

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

现在我有了字段 - 'myfield' - 那我怎么才能获取到这个字段的类呢?

如果这个字段是关联字段的话,怎么才能获取到相关的字段呢?

非常感谢!

4 个回答

4

如果你想查看Django模型对象上的所有字段,可以通过调用 ._meta.get_fields() 来实现。这可以在类上调用,也可以在一个已经创建的模型对象上调用,这样就能得到一个包含所有字段的列表。这个方法在最新版本的Django中都是适用的。

举个例子:

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

这个方法会返回一个包含所有模型字段的元组。你可以在 这里 找到相关的文档。

10

Anurag Uniyal 提到的使用 get_field_by_name 的方法,现在已经过时了,因为 get_field_by_name 已经不再推荐使用。Django 会给你这样的提示:

RemovedInDjango110Warning: 'get_field_by_name' 是一个非官方的API,已经被弃用。你可以用 'get_field()' 来替代它。

关于 get_field 的详细文档可以在 这里 找到。

74

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

撰写回答