[英]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.