django model meta ordering multiple ordering
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
date_created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-date_created', 'age', 'name']
Explanation:
Import the necessary module
models
fromdjango.db
.Create a Django model named
MyModel
that inherits frommodels.Model
.Define three fields within the
MyModel
class:name
: A character field (CharField
) with a maximum length of 100 characters.age
: An integer field (IntegerField
) to store age values.date_created
: A date and time field (DateTimeField
) set to automatically add the creation date and time when an object is created.
Inside the
MyModel
class, create a nested class namedMeta
. This inner class is used to specify metadata for the model.Within the
Meta
class, set theordering
attribute to a list of fields:-date_created
: Orders objects in descending order based on thedate_created
field. The minus sign (-
) denotes descending order.age
: Orders objects in ascending order based on theage
field.name
: Orders objects in ascending order based on thename
field.
This Meta
class with the ordering
attribute specifies the default ordering of querysets for this model. In this case, querysets of MyModel
will be ordered by date_created
in descending order, followed by age
in ascending order, and then by name
in ascending order.
```