Meta-metadata for models-Django from getting started to mastering series tutorials

Source: Internet
Author: User

This series of tutorials is personal original, and fully published in the personal website Liu Jiang's blog and tutorials all reproduced herein, need to be prominently marked on the top of the original author and www.liujiangblog.com website address. Python and Django Learning QQ Group: 453131687

The metadata of the model refers to everything except the field, such as the Sort method, database table name, human readable singular or plural name, and so on. All of these are non-essential, even the metadata itself is not necessary for the model. However, I would like to say that some meta-data options can be of great help to you and are important in practical use, which is the ' must ' for practical applications.

To add metadata to the model, the method is simple, adding a subclass to the model class, the name fixed Meta , and then adding a variety of meta-data options or set items under the Meta class. Refer to the following example:

fromimport modelsclass Ox(models.Model):    = models.IntegerField()    class Meta:         # 注意,是模型的子类,要缩进!        = ["horn_length"]        ="oxen"

In the example above, we have added two metadata ' ordering ' and ' verbose_name_plural ' to the Model Ox, respectively, for the sort and plural names, and we'll show you what metadata options are available in detail below.

It is emphasized that each model can have its own metadata class, and that each meta-data class only works on its own model.

Abstract

If abstract=True so, then the model will be considered an abstract model. The abstract model itself does not actually generate database tables, but is used as the parent of other models and is inherited. Specific content can refer to the Django model inheritance.

App_label

If the app that defines the model is not INSTALLED_APPS registered in, you must declare which app it belongs to by using this meta option, for example:

app_label = 'myapp'
Base_manager_name

The name of the _base_manager manager of the custom model. The model manager is where Django provides the API for the model. Django1.10 added.

Db_table

Specifies the table name of the data table that is generated by the current model in the database. Like what:

db_table = 'my_freinds'

Friendly advice: Use the MySQL database when using db_table lowercase English.

Db_tablespace

The name of the custom database table space. The default value is the project's DEFAULT_TABLESPACE setting.

Default_manager_name

The name of the _default_manager manager of the custom model. Django1.10 added.

Default_related_name

By default, the source model with relational fields is set from a model inverse association, which we use <model_name>_set , that is, the source model's name + underscore + set .

This meta-data option allows you to customize the inverse relationship name and also affect the inverse query relationship name! Look at the following example:

fromimport modelsclass Foo(models.Model):    passclass Bar(models.Model):    = models.ForeignKey(Foo)    class Meta:        ='bars'   # 关键在这里

The specific usage differences are as follows:

>>> bar = Bar.objects.get(pk=1)>>> # 不能再使用"bar"作为反向查询的关键字了。>>> Foo.objects.get(bar=bar)>>> # 而要使用你自己定义的"bars"了。>>> Foo.objects.get(bars=bar)
Get_latest_by

The Django Manager gives us the latest () and earliest () methods, respectively, to get the nearest and last data objects. But how to judge the most recent one and the front one? What sort is that?

get_latest_byThe metadata option solves this problem by specifying a similar DateField , or sort of, DateTimeField IntegerField field that can be sorted by the latest () and earliest () methods to derive the most recent or previous object. For example:

get_latest_by = "order_date"
Managed

The default value of this metadata is true, which means that Django will manage the life cycle of the database tables in accordance with established rules.

If set to False, database tables are not created and deleted for the current model. In some scenarios, this may be useful, but more often, you can forget the option.

Order_with_respect_to

This option is not easy to understand. Its purpose is to sort according to the specified field, which is typically used for relationship fields. Look at the following example:

fromimport modelsclass Question(models.Model):    = models.TextField()    # ...class Answer(models.Model):    = models.ForeignKey(Question, on_delete=models.CASCADE)    # ...    class Meta:        ='question'

The above is set in the answer model order_with_respect_to = ‘question‘ , so Django will automatically provide two APIs, and, in this case, a get_RELATED_order() set_RELATED_order() RELATED lowercase model name instead. Assuming that there is now a question object that is associated with multiple answer objects, the following operation returns a list of the primary keys that contain the associated Anser object []:

>>> question = Question.objects.get(id=1)>>> question.get_answer_order()[1, 2, 3]

We can set_RELATED_order() specify the order of the above list by means of the method:

>>> question.set_answer_order([3, 1, 2])

Similarly, the associated object also obtains two methods get_next_in_order() and is get_previous_in_order() used to access the object in a specific order, as follows:

>>> answer = Answer.objects.get(id=2)>>> answer.get_next_in_order()<Answer: 3>>>> answer.get_previous_in_order()<Answer: 1>

The role of this meta-data ... It's not working, it's embarrassing.

Ordering

One of the most commonly used meta-data!

Used to specify how all objects generated by the model are sorted, and receive a tuple or list of field names. By default in ascending order, if the character "-" is preceded by the field name, it is sorted in descending order, if the character question mark is used? "indicates a random arrangement. Take a look at the following example:

ordering = ['pub_date']             # 表示按'pub_date'字段进行升序排列ordering = ['-pub_date']            # 表示按'pub_date'字段进行降序排列ordering = ['-pub_date', 'author']  # 表示先按'pub_date'字段进行降序排列,再按`author`字段进行升序排列。
Permissions

This metadata is used to add additional permissions when the object is created. It receives a list of all elements that are two tuples or tuples, each of which is (权限代码, 直观的权限名称) in the format. For example, the following:

permissions = (("can_deliver_pizzas", "可以送披萨"),)
Default_permissions

Django defaults to all of the model settings (' Add ', ' Change ', ' delete ') permissions, which are added to the deletion. You can customize this option, such as setting an empty list to indicate that you do not need the default permissions, but this must be done before the Migrate command is executed.

Proxy

If set proxy = True , represents how model inheritance is used in proxy mode. As with the abstract option, the reference model inherits the chapter.

Required_db_features

Declares the database functionality that the model relies on. For example, [' gis_enabled '], which indicates that the model is built on GIS functions.

Required_db_vendor

Declares the database supported by the model. Django is supported by default sqlite, postgresql, mysql, oracle .

Select_on_save

Determines whether the object is saved using an algorithm prior to version 1.6 django.db.models.Model.save() . The default value is False. We don't usually care about this option.

Indexes

Django1.11 the new options.

Receives a list of indexes applied to the current model, as shown in the following example:

from django.db import modelsclass Customer(models.Model):    first_name = models.CharField(max_length=100)    last_name = models.CharField(max_length=100)    class Meta:        indexes = [            models.Index(fields=['last_name', 'first_name']),            models.Index(fields=['first_name'], name='first_name_idx'),        ]
Unique_together

This meta-data is very important one! It is equivalent to the federated constraints of the database!

For example, suppose you have a user table that holds information about the user's name, date of birth, gender and place of origin, and so on. The requirement is that all users only do not repeat, but now there are several called "Zhang Wei", how to distinguish them? (Don't tell me the primary key is the only one, this is not the problem discussed here)

We can set up no more than two users in the same place at the same time and are called "Zhang Wei", using this combination of constraints, to ensure that the database can not repeat the addition of users (also don't talk to me about the small probability problem). How do you implement this constraint in a Django model?

Use unique_together , that is, union only!

Like what:

unique_together = (('name', 'birth_day', 'address'),)

In this way, even if there are two born on the same day Zhang Wei, but their native origin is different, that is, two different users. Once all three are the same, Django will reject the creation. This meta data is often used in the admin background and enforced at the database level.

Unique_together receives a two-dimensional tuple ((xx,xx,xx,...), (), (), () ...), each element is a tuple that represents a set of federated unique constraints that can be set at the same time for multiple sets of constraints. For convenience, one-dimensional elements can be simply used in cases where there is only one set of constraints, for example:

unique_together = ('name', 'birth_day', 'address')

Union only cannot be used for normal many-to-many fields.

Index_together

Obsolete, use index meta data instead.

Verbose_name

One of the most commonly used meta data! An intuitive, human-readable name for setting model objects. Can be in Chinese. For example:

verbose_name = "story"verbose_name = "披萨"

If you do not specify it, Django uses the lowercase model name as the default value.

Verbose_name_plural

English has singular and plural forms. This is the name of the duplicate of the model object, such as "apples". Because we do not usually distinguish between the single plural, so verbose_name it is also possible to maintain and consistent.

verbose_name_plural = "stories"verbose_name_plural = "披萨"

If you do not specify this option, then the default plural name is verbose_name plus ' s '

Label

The metadata described earlier is modifiable and set, but there are two read-only metadata, and label is one of them.

Label is equivalent to app_label.object_name . For example polls.Question , polls is the name of the application and question is the model name.

Label_lower

Ditto, but a lowercase model name.

Meta-metadata for models-Django from getting started to mastering series tutorials

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.