4👍
✅
You can make use of the Coalesce
function [Django-doc] to provide a value if Max('comments__created')
returns NULL
(this happens if there are no values over which to aggregate:
from django.db.models.functions import Coalesce
posts = posts_all.annotate(
max_activity=Coalesce(Max('comments__created'), 'published_date')
).order_by('-max_activity')
Source:stackexchange.com