Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Order By Date, but have "None" at end?

I have a model of work orders, with a field for when the work order is required by. To get a list of work orders, with those that are required early, I do this:

wo = Work_Order.objects.order_by('dateWORequired')

This works nicely, but ONLY if there is actually a value in that field. If there is no required date, then the value is None. Then, the list of work orders has all the None's at the top, and then the remaining work orders in proper order.

How can I get the None's at the bottom?

like image 974
Garfonzo Avatar asked Oct 13 '11 03:10

Garfonzo


People also ask

How to set a field as primary key in Django?

If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).

What is inheritance in Django?

In multi-table inheritance, each model corresponds to a database table. Django creates a OneToOneField field for the relationship in the child's model to its parent. Django would include an automatically generated OneToOneField field in the Text model and create a database table for each model.

What is proxy model in Django?

Proxy models allow us to change the Python behavior of a model without changing the database. vehicles/models.py. from django.db import models. class Car(models.Model): vin = models.CharField(max_length=17)

What is the model in Django?

Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc.


1 Answers

Django 1.11 added this as a native feature. It's a little convoluted. It is documented.

Ordered with only one field, ascending:

wo = Work_Order.objects.order_by(F('dateWORequired').asc(nulls_last=True)) 

Ordered using two fields, both descending:

wo = Work_Order.objects.order_by(F('dateWORequired').desc(nulls_last=True), F('anotherfield').desc(nulls_last=True)) 
like image 129
Ric W Avatar answered Oct 08 '22 19:10

Ric W