Django Model._meta API

2021-07-13 09:07

阅读:440

标签:doc   ping   efi   The   ack   user   .com   another   with   

Model._meta API是Django ORM的核心,它使得lookups、queries、forms、admin这些模块通过每个model类的_meta的属性可以了解每个model的情况。

1. 字段访问API,使用名字检索一个model的字段实例

Options.get_field(field_name) 

根据给出的field_name返回一个字段实例。field_name可以是model中的字段,抽象或者继承model的字段,或者指向一个model的另一个model上的字段,最后这种情况中的field_name是用户定义的related_name或者是Django自动产生的名字。

note:隐藏的字段不能通过名字检索。如果给出的字段名找不到,会抛出FieldDoesNotExist的错误。

  1.  
    >>> from django.contrib.auth.models import User
  2.  
     
  3.  
    # A field on the model
  4.  
    >>> User._meta.get_field(‘username‘)
  5.  
  6.  
     
  7.  
    # A field from another model that has a relation with the current model
  8.  
    >>> User._meta.get_field(‘logentry‘)
  9.  
  10.  
     
  11.  
    # A non existent field
  12.  
    >>> User._meta.get_field(‘does_not_exist‘)
  13.  
    Traceback (most recent call last):
  14.  
    ...
  15.  
    FieldDoesNotExist: User has no field named ‘does_not_exist‘

 

2. 检索一个model的所有字段实例
Options.get_fields(include_parents=True, include_hidden=False)

以元组的形式返回一个model的相关的所有字段。get_fields接收两个参数用来控制要返回哪些字段。

  1.  
    >>> from django.contrib.auth.models import User
  2.  
    >>> User._meta.get_fields()
  3.  
    (,
  4.  
    ,
  5.  
    ,
  6.  
    ,
  7.  
    ,
  8.  
    ,
  9.  
    ,
  10.  
    ,
  11.  
    ,
  12.  
    ,
  13.  
    ,
  14.  
    ,
  15.  
    ,
  16.  
    )

原文链接:https://docs.djangoproject.com/en/2.0/ref/models/meta/

 

Django Model._meta API

标签:doc   ping   efi   The   ack   user   .com   another   with   

原文地址:https://www.cnblogs.com/qunxiadexiaoxiangjiao/p/9574624.html


评论


亲,登录后才可以留言!