標籤:date entry block gen iter 包含 cti 訪問 通過
一:Model
_meta API
模型_metaAPI是Django ORM的核心。它使系統的其他部分(如查詢,查詢,表單和管理員)瞭解每個模型的功能。
API可以通過_meta每個模型類的屬性來訪問,這是一個django.db.models.options.Options對象的一個執行個體 。
它提供的方法可以用來:
- 檢索模型的所有欄位執行個體
- 按名稱檢索模型的單個欄位執行個體
二:Model
_meta常用方式 1)按名稱檢索模型的單個欄位執行個體
Options.get_field(field_name)[source] ,回給定欄位名稱的欄位執行個體。
field_name可以是模型上欄位的名稱,抽象或繼承模型上的欄位,或指向模型的另一個模型上定義的欄位。
在後一種情況下,field_name 將由related_name使用者定義或由Django本身自動產生的名稱。
Hidden fields 不能被名字檢索。
如果沒有找到具有給定名稱的欄位, FieldDoesNotExist則會引發異常
>>> from django.contrib.auth.models import User# A field on the model>>> User._meta.get_field(‘username‘)<django.db.models.fields.CharField: username># A field from another model that has a relation with the current model>>> User._meta.get_field(‘logentry‘)<ManyToOneRel: admin.logentry># A non existent field>>> User._meta.get_field(‘does_not_exist‘)Traceback (most recent call last): ...FieldDoesNotExist: User has no field named ‘does_not_exist‘
View Code2)檢索模型的所有欄位執行個體
-
Options.
get_fields(
include_parents = True,
include_hidden = False)[source]
-
返回與模型關聯的欄位的元組。get_fields()接受可以用來控制返回哪些欄位的兩個參數:
-
include_parents
-
True預設。遞迴地包含在父類上定義的欄位。如果設定為
False,
get_fields()只會搜尋直接在當前模型上聲明的欄位。直接從抽象模型或代理類繼承的模型中的欄位被認為是本地的,而不是父類。
-
include_hidden
-
False預設。如果設定為
True,
get_fields()將包含用於支援其他欄位功能的欄位。這也將包括任何有一個
related_name(如
ManyToManyField,或
ForeignKey)以“+”開頭的欄位。
>>> from django.contrib.auth.models import User>>> User._meta.get_fields()(<ManyToOneRel: admin.logentry>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.CharField: password>, <django.db.models.fields.DateTimeField: last_login>, <django.db.models.fields.BooleanField: is_superuser>, <django.db.models.fields.CharField: username>, <django.db.models.fields.CharField: first_name>, <django.db.models.fields.CharField: last_name>, <django.db.models.fields.EmailField: email>, <django.db.models.fields.BooleanField: is_staff>, <django.db.models.fields.BooleanField: is_active>, <django.db.models.fields.DateTimeField: date_joined>, <django.db.models.fields.related.ManyToManyField: groups>, <django.db.models.fields.related.ManyToManyField: user_permissions>)
View Code
django-Model _meta API