栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 面试经验 > 面试问答

如何自省Django模型字段?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何自省Django模型字段?

您可以使用模型的

_meta
属性来获取字段对象,并且可以从字段中获取关系以及更多其他信息,例如,考虑一个雇员表,该雇员表具有一个部门表的外键

In [1]: from django.db import modelsIn [2]: model = models.get_model('timeapp', 'Employee')In [3]: dep_field = model._meta.get_field_by_name('department')In [4]: dep_field[0].target_fieldOut[4]: 'id'In [5]: dep_field[0].related_modelOut[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.    """


转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/639995.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号