How to Set the Ordering of a Database Table By Column in the models.py File in Django



Python


In this article, we show how to set the ordering of a database table by column in the models.py file in Django.

So when you create a model (database table) in the models.py file in Django, by default, the items of the model will go in order from first created (showing first) to last created (showing last).

However, you may not want the results of the table shown in this way.

You may want the items sorted by price from least to greatest (assuming the model has a price column).

You may want the names of customers alphabetized (assuming the model has a customers column).

Any way that you want the data to be sorted when shown can be set in the models.py file.

When creating the model in the models.py file, underneath the definitions of the columns of the models, we can create a Meta class and the define the ordering attribute.

In the ordering attribute, we specify which column we want to order the model by.

This is shown in the following code below.



So let's go over the code now.

So, in this code, we have created a model named Blog.

It has title, slug, content, pub_date, and last_edited columns.

We want to order the model from the latest publication date showing first and the earlier publication dates showing last.

Therefore, we create a nested meta class for the model.

Within this nested meta class, we specify a column for the ordering attribute.

In this ordering attribute, we want to order the model from the latest publication dates showing first; therefore, we specify the '-pub_date' in the ordering attribute.

And this is how we can set the ordering of a database table (model) in the models.py file in Django.

Of course, there are other ways you can order a model than this way.

For example, in the views.py file, you can use the order_by() function in Django to order the table according to any column.

However, if you know you want the table ordered in a certain way and only in one way, setting the value of the ordering attribute in the models.py file is probably the purest way of coding.

And this is how to order a database table by column in the models.py file in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...