Tuesday, June 29, 2021

Model Meta Options in Django

db_table

Options.db_table

The name of the database table to use for the model:

db_table = 'music_album'



Table names

To save you time, Django automatically derives the name of the database table from the name of your model class and the app that contains it. A model’s database table name is constructed by joining the model’s “app label” – the name you used in manage.py startapp – to the model’s class name, with an underscore between them.

For example, if you have an app bookstore (as created by manage.py startapp bookstore), a model defined as class Book will have a database table named bookstore_book.

To override the database table name, use the db_table parameter in class Meta.



verbose_name

Options.verbose_name

A human-readable name for the object, singular:

verbose_name = "pizza"

If this isn’t given, Django will use a munged version of the class name: CamelCase becomes camel case.



verbose_name_plural

Options.verbose_name_plural

The plural name for the object:

verbose_name_plural = "stories"

If this isn’t given, Django will use verbose_name + "s".



Read-only Meta attributes

label

Options.label

Representation of the object, returns app_label.object_name, e.g. 'polls.Question'.

label_lower

Options.label_lower

Representation of the model, returns app_label.model_name, e.g. 'polls.question'.



constraints

Options.constraints

A list of constraints that you want to define on the model:

from django.db import models


class Customer(models.Model):

    age = models.IntegerField()


    class Meta:

        constraints = [

            models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),

        ]



Others few are


index_together = [

    ["pub_date", "deadline"],

]


unique_together = [['driver', 'restaurant']]



Indexes to be used in place of index_together. 


class Meta:

        indexes = [

            models.Index(fields=['last_name', 'first_name']),

            models.Index(fields=['first_name'], name='first_name_idx'),

        ]



ordering

Options.ordering

The default ordering for the object, for use when obtaining lists of objects:



ordering = ['-order_date']

ordering = ['pub_date']

ordering = ['-pub_date']

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

ordering = [F('author').asc(nulls_last=True)]




References:

https://docs.djangoproject.com/en/3.2/ref/models/options/

No comments:

Post a Comment