如何内省django模型领域? [英] How to introspect django model fields?

查看:118
本文介绍了如何内省django模型领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我只知道模型的名称和模型的名称(两个简单的字符串)时,我正在尝试获取一个模型中字段的类信息。如何可能?



我可以动态加载模型:

 从django.db导入模型
model = models.get_model('myapp','mymodel')

现在我有字段 - 'myfield' - 如何获得该字段的类?



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



感谢一堆!

解决方案

您可以使用模型的 _meta 属性来获取字段对象,从字段可以获得关系等等考虑一个具有外部部门表外键的员工表

 在[1]中:从django.db导入模型

在[2]中:model = models.get_model('timeapp','Employee')

在[3]中:dep_field = model._meta.get_field_by_name('department')

在[4]中:dep_field [0] .rel.field_name
Out [4]:'id'

在[5]中:dep_field [0] .rel.to
Out [5]:< class'timesite.timeapp.models.Department'>

from django / db / models / options.py


$ b $
$
返回(field_object,model,direct,m2m),其中field_object是
给定名称的Field实例,model是包含
此字段的模型(对于本地字段为None),如果该模型上的字段存在
,则为true,对于多个对象,m2m为True当
'direct'为False时,'field_object'是该字段对应的相应对象
(因为该字段没有与之相关联的实例


在内部使用缓存,所以在第一次访问后,这是非常快的


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!

解决方案

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].rel.field_name
Out[4]: 'id'

In [5]: dep_field[0].rel.to
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.
    """

这篇关于如何内省django模型领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆