zoukankan      html  css  js  c++  java
  • Django Model._meta API

    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.  
      <django.db.models.fields.CharField: username>
    6.  
       
    7.  
      # A field from another model that has a relation with the current model
    8.  
      >>> User._meta.get_field('logentry')
    9.  
      <ManyToOneRel: admin.logentry>
    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.  
      (<ManyToOneRel: admin.logentry>,
    4.  
      <django.db.models.fields.AutoField: id>,
    5.  
      <django.db.models.fields.CharField: password>,
    6.  
      <django.db.models.fields.DateTimeField: last_login>,
    7.  
      <django.db.models.fields.BooleanField: is_superuser>,
    8.  
      <django.db.models.fields.CharField: username>,
    9.  
      <django.db.models.fields.CharField: first_name>,
    10.  
      <django.db.models.fields.CharField: last_name>,
    11.  
      <django.db.models.fields.EmailField: email>,
    12.  
      <django.db.models.fields.BooleanField: is_staff>,
    13.  
      <django.db.models.fields.BooleanField: is_active>,
    14.  
      <django.db.models.fields.DateTimeField: date_joined>,
    15.  
      <django.db.models.fields.related.ManyToManyField: groups>,
    16.  
      <django.db.models.fields.related.ManyToManyField: user_permissions>)

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

     

  • 相关阅读:
    javascript 笔记
    i18n,国际化翻译,excel与js互转
    nginx 一个端口布署多个单页应用(history路由模式)。
    html, js,css应用文件路径规则
    vue响应式原理,去掉优化,只看核心
    js 大量数据优化,通用方法
    nginx 常用的location rewrite proxy_pass
    javascript,排列组合
    zk分布式任务管理
    springboot+mybatis+dubbo+aop日志终结篇
  • 原文地址:https://www.cnblogs.com/qunxiadexiaoxiangjiao/p/9574624.html
Copyright © 2011-2022 走看看