import logging
logger = logging.getLogger(__name__)

from django.db import models


def get_next_ordering(model, field_name='sort_order', increment=10):
    """
    Get the next available value for the sortorder for a model.

    Use case::

        class MyModel(models.Model):
            sort_order = models.PositiveSmallIntegerField(
                default=lambda: get_next_ordering(MyModel)
            )

    """
    aggregate = model.objects.aggregate(latest=models.Max(field_name))
    latest = aggregate['latest']

    if latest:
        return latest + increment
    else:
        return increment


def get_or_create_object(model, **kwargs):
    """
    Get or create feed entry with specified kwargs without saving.

    This behaves like Django's own get_or_create but it doesn't save the
    newly created object, allowing for further modification before saving
    without triggering an extra `save()` call.
    """

    try:
        # Updating an existing object
        db_entry = model.objects.get(**kwargs)

        logger.debug('Updating existing entry %s', db_entry)

    except model.DoesNotExist:
        # Creating a new object
        db_entry = model(**kwargs)

        logger.debug('Creating new entry %s', db_entry)

    return db_entry

@@ -104,16 +104,22 @@
 ng(model
+_or_qs
 , field_
@@ -152,16 +152,16 @@
 nt=10):%0A
-
     %22%22%22%0A
@@ -427,25 +427,146 @@
     
-aggregate
+if isinstance(model_or_qs, models.base.ModelBase):%0A        # If a model has been given, create QuerySet for all objects%0A        qs
  = model
 .obj
@@ -553,32 +553,38 @@
       qs = model
+_or_qs
 .objects.aggrega
@@ -576,16 +576,229 @@
 objects.
+all()%0A    else:%0A        # No model has been given, assert that the input is in fact%0A        # a QuerySet.%0A        assert isinstance(model_or_qs, models.query.QuerySet)%0A        qs = model_or_qs%0A%0A    aggregate = qs.
 aggregat

Allow QuerySets in get_next_ordering