Django——Meta详解

参考文献:

https://docs.djangoproject.com/zh-hans/2.0/topics/db/models/

https://docs.djangoproject.com/zh-hans/2.0/ref/models/options/

Meta选项

abstract

如果abstract=True,那么这个模型就是抽象的基类模型

app_label

这个选型只在一种情况下使用,就是你的模型不在默认的应用程序包下的models.py文件中,这时候需要指定你这个模型是哪个应用程序的。

Options.app_label
如果一个model定义在默认的models.py,例如如果你的app的models在myapp.models子模块下,你必须定义app_label让Django知道它属于哪一个app
app_label = 'myapp'

db_table

自定义数据库表的名称。db_table="my_table_name"

order_with_respect_to

能够以给定的字段进行排序。

from django.db import models

class Question(models.Model):
    text = models.TextField()
    # ...

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    # ...

    class Meta:
        order_with_respect_to = 'question'
>>> question = Question.objects.get(id=1)
>>> question.get_answer_order()
[1, 2, 3]

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

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

ordering

告诉django,按照那个字段来进行排序。实例如下:

按照‘pub_date’进行升序排序:

ordering = ['pub_date']

按照‘pub_date’进行降序排序:

ordering = ['-pub_date']

以“pub_date”降序,以‘author’升序:

ordering = ['-pub_date', 'author']

unique_together

设置联合唯一属性,实例如下:

unique_together = (("driver", "restaurant"),)
unique_together = ("driver", "restaurant")

verbose_name

给模型一个更加可读的名称。如果不设置的话,默认为原名称小写,并加空格分割。比如:CamelCase变为camel case

verbose_name_plural

复数形式的verbose_name

猜你喜欢

转载自www.cnblogs.com/aric-zhu/p/9349095.html