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:

  1. Import the necessary module models from django.db.

  2. Create a Django model named MyModel that inherits from models.Model.

  3. 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.
  4. Inside the MyModel class, create a nested class named Meta. This inner class is used to specify metadata for the model.

  5. Within the Meta class, set the ordering attribute to a list of fields:

    • -date_created: Orders objects in descending order based on the date_created field. The minus sign (-) denotes descending order.
    • age: Orders objects in ascending order based on the age field.
    • name: Orders objects in ascending order based on the name 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. ```