_meta Programming for Django Models

Source: Internet
Author: User

Python has a reflection mechanism, Django is no exception, there is a good reflection mechanism, each Django model has a property _meta,_meta also have properties and methods, these properties and methods reflect some of the characteristics of the model, if _meta good, Not only is the code more graceful, but it can also greatly improve the universality and reuse of the code. The following mainly describes the properties and methods of _meta.

In a Django project, define a model, and then use the Dir () function to print out the properties and methods of the model's _meta, as follows:

Properties and methods of _meta

' __class__ ', ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ', ' __init__ ', ' __module ' __ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ', ' _field_cache ', ' _field_name_cache ', ' _fields ', ' _fill_fields_cache ', ' _fill_m2m_cache ', ' _fill_ ' Related_many_to_many_cache ', ' _fill_related_objects_cache ', ' _join_cache ', ' _m2m_cache ', ' _many_to_many ', ' _name_ Map ', ' _prepare ', ' _related_many_to_many_cache ', ' _related_objects_cache ', ' _related_objects_proxy_cache ', ' Abstract ', ' abstract_managers ', ' Add_field ', ' Add_virtual_field ', ' admin ', ' app_label ', ' auto_created ', ' Auto_field ', ' Concrete_managers ', ' Concrete_model ', ' contribute_to_class ', ' db_table ', ' db_tablespace ', ' duplicate_targets ', ' Fields ', ' get_add_permission ', ' get_all_field_names ', ' Get_all_related_m2m_objects_with_model ', ' get_all_related_ Many_to_many_objects ', ' get_all_related_objects ', ' Get_all_related_objects_with_model ', ' Get_ancestor_link ', ' get_base_chain ', ' get_change_permission ', ' get_delete_permission ', ' Get_field ', ' get_field_by _name ', ' Get_fields_with_model ', ' get_latest_by ', ' Get_m2m_with_model ', ' get_ordered_objects ', ' get_parent_list ', ' Has_auto_field ', ' init_name_map ', ' Installed ', ' local_fields ', ' local_many_to_many ', ' managed ', ' many_to_many ', ' Module_name ', ' object_name ', ' order_with_respect_to ', ' ordering ', ' parents ', ' permissions ', ' PK ', ' pk_index ', ' Proxy ', ' Proxy_for_model ', ' related_fkey_lookups ', ' setup_pk ', ' setup_proxy ', ' unique_together ', ' verbose_name ', ' verbose_ ' Name_plural ', ' verbose_name_raw ', ' virtual_fields '


Here's a look at the main properties and methods of this.

_field_cache: The cache of a field type is a tuple that reflects the type of each field in the model and returns the following form:

(<DJANGO.DB.MODELS.FIELDS.AUTOFIELD:ID>, None), (<django.db.models.fields.datetimefield:create_time , none), (<django.db.models.fields.related.foreignkey:create_user>, none), (< Django.db.models.fields.datetimefield:write_time>, None), (<django.db.models.fields.related.foreignkey: Write_user>, none), (<django.db.models.fields.related.foreignkey:confirm_user>, none), (< Django.db.models.fields.datetimefield:confirm_date>, None))

_field_name_cache: Similar to the above _field_cache, the returned result form is as follows:

[<django.db.models.fields.autofield:id>, <django.db.models.fields.datetimefield:create_time>, < Django.db.models.fields.related.foreignkey:create_user>, <django.db.models.fields.datetimefield:write_ Time>, <django.db.models.fields.related.foreignkey:write_user>, < Django.db.models.fields.related.foreignkey:confirm_user>]

Abstract : A Boolean that indicates whether an abstract class is not instantiated. Since Python does not have the concept of abstract classes and interfaces, it is possible to implement this function ABC module

abstract_managers: Returns the abstract manager list, which is the interface of the Django model for database query operations. Each model of a Django application has at least one manager

Add_field (): inserts fields sequentially, function prototypes Add_field (field, Private=false, virtual=not_provided), and the file parameter is a field type instance. Can participate in this part of the source code, links as follows https://github.com/django/django/blob/master/django/db/models/base.py

Add_virtual_field (): Add a dummy field, function prototype Add_virtual_field (field, Varargs=none, Keywords=none, Defaults=none), available _meta The virtual_fields property can view all the virtual fields under the model,

App_label: property, the name of the app package in which the model resides

auto_created: Boolean value that indicates whether to automatically create

Auto_field: property that returns all fields of the field type, usually the ' id ' field, such as <django.db.models.fields.AutoField:id>

concrete_managers: Returns a specific list of managers, by default, Django adds a manager named objects for each model class, so by default, the value means at least one objects manager. If you customize the manager, the custom manager can be obtained from this property.

Concrete_model: property that returns the model itself, through which the property value can be used '. ' Manipulate the properties of a field that accesses it, including the field name, whether it can be empty, and so on

Contribute_to_class (): do not know what role, source https://github.com/django/django/blob/master/django/db/models/options.py

db_table: property, the name of the data table used by the model, the name of the data table, can be found in the Django document, http://python.usyiyi.cn/django/ref/models/options.html

db_tablespace: The name of the database table space used by the current model. The default value is default_tablespace in the project settings, if it exists

duplicate_targets: Property, the return value is a dictionary, which indicates that the field property in the model is just a field with a different name, such as the following example:

From django.db import modelsfrom django.contrib.auth.models import userclass  a (models. Model):     create_time = models. Datetimefield (auto_now_add=true)     create_user = models. ForeignKey (user,related_name= '% (App_label) s_% (Class) S_create_user ')     write_time =  models. Datetimefield (auto_now=true,blank=true,null=true)     write_user = models. ForeignKey (user,related_name= '% (App_label) s_% (Class) S_write_user ', blank=true)     confirm_ User = models. ForeignKey (User,blank=true,null=true,)     confirm_date = models. Datetimefield (blank=true,null=true)     owner = models. ForeignKey (user,related_name= ' Purchases_owner ')     review = models. ForeignKey (user,blank=true, null=true,related_name= ' review ')

Then the value of A._meta.duplicate_targets is {' create_user_id ': Set ([' review_id ', ' write_user_id ', ' owner_id ']), ' review_id ': Set ([' create_user_id ', ' write_user_id ', ' owner_id ']), ' write_user_id ': Set ([' create_user_id ', ' review_id ', ' owner_id ']) , ' owner_id ': Set ([' create_user_id ', ' review_id ', ' write_user_id ')}

They all relate to the class one user.

Fields : property, returns a list of all the field of the model, as follows [<django.db.models.fields.autofield:id>, < Django.db.models.fields.datetimefield:create_time>, <django.db.models.fields.related.foreignkey:create_ User>, <django.db.models.fields.datetimefield:write_time>, < Django.db.models.fields.related.foreignkey:write_user>, <django.db.models.fields.related.foreignkey: Parent>, <django.db.models.fields.charfield:state>, <django.db.models.fields.related.foreignkey: Owner>, <django.db.models.fields.related.foreignkey:review>, <django.db.models.fields.charfield:name , <django.db.models.fields.charfield:tags>,]

We know that a field is actually an object, and its properties can reflect the properties of the field, which is the model field options, such as Verbose_name, name, Primary_key,max_length, Unique, Blank and so on (field class source see https://github.com/django/django/blob/master/django/db/models/fields/__init__.py, Model field option meaning see http://python.usyiyi.cn/django/ref/models/fields.html)

get_add_permission (): get "Add" permission, return a string, similar to get_change_permission (), Get_delete_permission ()

Get_all_field_names (): Returns a list of all the field names of the model, and how do you understand all of this? This includes not only the fields defined by the model itself, but also the fields associated with it in other models (i.e., Foreignkey,manytomanyfield,onetoonefield)

Get_all_related_m2m_objects_with_model (): Gets all the models that have manytomanyfield relationships to the model, returning a list, such as [(<relatedobject:human: Humansupplier related to User>, none), (<relatedobject:human:humanrole related to User>, none)]

get_all_related_many_to_many_objects (): similar to the above method, except that the return value has a slightly different form [<relatedobject:human:humansupplier related to User> <relatedobject:human:humanrole related to User>], similar to get_all_related_objects (), Get_all_related_objects_with_model ()to get all the models that have an association with the model

Get_field (): prototype Get_field (name,many_to_many=true), Field_name is a string that returns the field name of the field that corresponds to Fields Field object, such as < Django.db.models.fields.related.foreignkey:create_user>, if the field name does not exist, returns a Fielddoesnotexist exception

get_field_by_name (): ibid., the return value is richer than the above (<DJANGO.DB.MODELS.FIELDS.RELATED.FOREIGNKEY:CREATE_USER>, None , true, False), respectively (Field_object, model, direct, ATM), if the model exists for this field, direct is true, and if the model has a manytomanyfield relationship, then the

Get_fields_with_model (): Returns the (field, model) pair sequence for all fields of the model, the model for fields on the current model, the element is not

get_latest_by: property that returns the name of a sortable field in the model, and if you define the value of get_latest_by in the meta-options of the model, the _meta.get_latest_ By returns the value of the get_latest_by defined in the meta-option, otherwise none is returned, for meta options , see Django Document Http://python.usyiyi.cn/django/ref/models/options.html

Get_m2m_with_model (): is the many-to-many version of Get_fields_with_model ()

get_ordered_objects (): Returns a list of options objects sorted by this object

Has_auto_field: property that returns a Boolean value that indicates that the model has no self-increment fields

Init_name_map (): Initializes the mapping of the field name to the Field object (that is Field object).

installed: attribute, Boolean, whether the app in which the model resides is configured in a Django setting file, which is the name of the app that contains the model in the setting file Installed_apps

Local_fields: property that returns all the local fields of the model, the return value is a list, the element is the field type

Local_many_to_many: property that returns all the fields of the model that are many_to_many relationships, excluding its parent class, the return value is a list, and similarly a many_to_many returns all the Many_ in the model and its parent class. A list of To_many relationship fields.

managed: Properties, Boolean

module_name: property, returns the model name , is lowercase, the type is a string

object_name: property, model name, string, but not lowercase, what name is used to define the model what name is displayed here, is the prototype

Ordering: property that returns the default order of a list of objects. If you define the value of ordering in the meta options of the model, _meta.ordering returns the value of the ordering defined in the META option, otherwise it returns []

Permissions: property that returns a list that returns the additional permissions in the permission table when the object is created. If you have defined the value of permissions in the meta options of the model, then _ Meta.permissions returns the value of the permissions defined in the meta-option, otherwise returns [], similar to this mechanism is Unique_together, Verbose_name, Verbose_name_plural, Verbose_name_raw

PK: property, return primary key field type

Pk_index (): method that returns the index of the primary key field in the Fields list.

Hopefully it will help you when using Django, and you're welcome to criticize it!

This article is from the "11016142" blog, please be sure to keep this source http://11026142.blog.51cto.com/11016142/1882835

_meta Programming for Django Models

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.