class Greatest(*expressions, **extra)
[source]
New in Django 1.9.
Accepts a list of at least two field names or expressions and returns the greatest value. Each argument must be of a similar type, so mixing text and numbers will result in a database error.
Usage example:
class Blog(models.Model): body = models.TextField() modified = models.DateTimeField(auto_now=True) class Comment(models.Model): body = models.TextField() modified = models.DateTimeField(auto_now=True) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) >>> from django.db.models.functions import Greatest >>> blog = Blog.objects.create(body='Greatest is the best.') >>> comment = Comment.objects.create(body='No, Least is better.', blog=blog) >>> comments = Comment.objects.annotate(last_updated=Greatest('modified', 'blog__modified')) >>> annotated_comment = comments.get()
annotated_comment.last_updated
will be the most recent of blog.modified
and comment.modified
.
Warning
The behavior of Greatest
when one or more expression may be null
varies between databases:
- PostgreSQL:
Greatest
will return the largest non-null expression, ornull
if all expressions arenull
. - SQLite, Oracle, and MySQL: If any expression is
null
,Greatest
will returnnull
.
The PostgreSQL behavior can be emulated using Coalesce
if you know a sensible minimum value to provide as a default.
Please login to continue.