Django: Adding "Nulls Last" to Query

Django: Adding NULLS LAST to query

from django.db.models import F  
MyModel.objects.all().order_by(F('price').desc(nulls_last=True))

This functionality has been added to Django 1.11.

https://docs.djangoproject.com/en/dev/releases/1.11/

Added the nulls_first and nulls_last parameters to Expression.asc()
and desc() to control the ordering of null values.

Reference for Django 3.1: https://docs.djangoproject.com/en/3.1/ref/models/expressions/#using-f-to-sort-null-values

Django NULLS LAST for creating Indexes

No, unfortunately, that is currently (Django <=2.1) not possible. If you look at the source of models.Index, you will see that it assumes that the argument fields contains model names and nothing else.

As a workaround, you could manually create your index with raw SQL in a migration.

Django Order By Date, but have None at end?

q = q.extra(select={
'date_is_null': 'dateWORequired IS NULL',
},
order_by=['date_is_null','dateWORequired'],
)

You might need a - before the date_is_null in the order_by portion, but that's how you can control the behavior.

Why does nulls_last=False not put the nulls first in Django?

The mistake is assuming that the opposite of nulls_last=True is nulls_last=False. It isn't.

nulls_last=True does the following to the query:

SELECT ... ORDER BY ... ASC NULLS LAST

Whereas nulls_last=False just means use the DB default:

SELECT ... ORDER BY ... ASC

What you want instead is to use nulls_first=True OR nulls_last=True to explicitly get the order you want.

This is mentioned in the docs, but perhaps not as explicitly as it could be:

Using F() to sort null values

Use F() and the nulls_first or
nulls_last keyword argument to Expression.asc() or desc() to control
the ordering of a field’s null values. By default, the ordering
depends on your database.

oder by nulls first in descending order in django

From django documentation

Using F() to sort null values

Use F() and the nulls_first or nulls_last keyword argument to
Expression.asc() or desc() to control the ordering of a field’s null
values. By default, the ordering depends on your database.

For example, to sort companies that haven’t been contacted
(last_contacted is null) after companies that have been contacted:

from django.db.models import F 
Company.objects.order_by(F('last_contacted').desc(nulls_last=True))

Django admin: order by a nullable date, with null values at the end

You can use query expressions. To order by completed ascending and make null values sort last, use this:

from django.db.models import F

ordering = [F('completed').desc(nulls_last=True)]

Source :https://docs.djangoproject.com/en/dev/ref/models/options

Django order_by two fields, with first field nulls last

I think I found the solution:

Person.objects.order_by(F('timestamp').asc(nulls_last=True), 'name')



Related Topics



Leave a reply



Submit