如何内省django模型领域?

编程入门 行业动态 更新时间:2024-10-25 03:16:36
本文介绍了如何内省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模型领域?

本文发布于:2023-11-25 13:48:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630004.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   领域   django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!