Search code examples
pythondjangodjango-queryset

Using max() with Django query


Is there a way to make this query work with Django?

stage = Task.objects.filter(id = input_stage.id)\
            .update(start_date = max(data.get('start_date'), F('start_date')),
                    finish_date = max(data.get('finish_date'), F('finish_date')))

Now I get an error:

TypeError: '>' not supported between instances of 'F' and 'datetime.date'

Solution

  • The max between two fields in a database is in Django the Greatest [Django-doc], so the query should read something like:

    from django.db.models import F, Value
    from django.db.models.functions import Greatest
    
    Task.objects.filter(
        id=input_stage.id
    ).update(
        start_date=Greatest(Value(data.get('start_date')), F('start_date')),
        finish_date=Greatest(Value(data.get('finish_date')), F('finish_date'))
    )

    You also might want to convert the data.get('start_date'), etc. to date objects.

    Mind that a .update(…) [django-doc] does not return a QuerySet, but:

    (...) and returns the number of rows matched (which may not be equal to the number of rows updated if some rows already have the new value).