django-Model _meta API

來源:互聯網
上載者:User

標籤:date   entry   block   gen   iter   包含   cti   訪問   通過   

 

一:Model  _meta API

  模型_metaAPI是Django ORM的核心。它使系統的其他部分(如查詢,查詢,表單和管理員)瞭解每個模型的功能。

  API可以通過_meta每個模型類的屬性來訪問,這是一個django.db.models.options.Options對象的一個執行個體 。

  它提供的方法可以用來:

  • 檢索模型的所有欄位執行個體
  • 按名稱檢索模型的單個欄位執行個體
二:Model  _meta常用方式  1)按名稱檢索模型的單個欄位執行個體

    Options.get_fieldfield_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_fieldsinclude_parents = Trueinclude_hidden = False)[source] 

返回與模型關聯的欄位的元組。get_fields()接受可以用來控制返回哪些欄位的兩個參數:

include_parents
True預設。遞迴地包含在父類上定義的欄位。如果設定為 Falseget_fields()只會搜尋直接在當前模型上聲明的欄位。直接從抽象模型或代理類繼承的模型中的欄位被認為是本地的,而不是父類。
include_hidden
False預設。如果設定為 Trueget_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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.