Increment the sort_order in a queryset.

        Handle IntegrityErrors caused by unique constraints.
542465
def _update(qs):
        
        try:
            with transaction.atomic():
                qs.update(sort_order=models.F('sort_order') + 1)
        except IntegrityError:
            for obj in qs.order_by('-sort_order'):
                qs.filter(pk=obj.pk).update(sort_order=models.F('sort_order') + 1)
55021
def update(self, values, **context):
        
        schema = self.schema()
        column_updates = {}
        other_updates = {}
        for key, value in values.items():
            try:
                column_updates[schema.column(key)] = value
            except orb.errors.ColumnNotFound:
                other_updates[key] = value

        # update the columns in order
        for col in sorted(column_updates.keys(), key=lambda x: x.order()):
            self.set(col, column_updates[col], **context)

        # update the other values
        for key, value in other_updates.items():
            try:
                self.set(key, value, **context)
            except orb.errors.ColumnValidationError:
                pass

        return len(values)
696541
def filter_queryset(self, request, queryset, view):
        "
        self.ordering_param = view.SORT

        ordering = self.get_ordering(request, queryset, view)
        if ordering:
            return queryset.order_by(*ordering)

        return queryset
185035
def order(self, order):
        
        if order is None:
            raise ValueError("Invalid value for `order`, must not be `None`")
        allowed_values = ["ASC", "DESC"]
        if order not in allowed_values:
            raise ValueError(
                "Invalid value for `order` ({0}), must be one of {1}"
                .format(order, allowed_values)
            )

        self._order = order
716517
def first(self, count=1):
        
        if count == 0:
            raise QueryInvalid("Count cannot be zero.")
        self.limit_count = count
        records = self._do_query().fetchall()
        if not records:
            return None
        if count == 1:
            record = records[0]
            args = dict(zip(self.attributes, record))
            return self.model.from_dict(**args)
        return self
310513
def order_queryset(self, queryset):
        
        order = self.derive_ordering()

        # if we get our order from the request
        # make sure it is a valid field in the list
        if '_order' in self.request.GET:
            if order.lstrip('-') not in self.derive_fields():
                order = None

        if order:
            # if our order is a single string, convert to a simple list
            if isinstance(order, str):
                order = (order,)

            queryset = queryset.order_by(*order)

        return queryset
335447
protected void addSortedModifications(List<DbOperation> flush) {

    // calculate sorted set of all modified entity types
    SortedSet<Class<?>> modifiedEntityTypes = new TreeSet<Class<?>>(MODIFICATION_TYPE_COMPARATOR);
    modifiedEntityTypes.addAll(updates.keySet());
    modifiedEntityTypes.addAll(deletes.keySet());
    modifiedEntityTypes.addAll(bulkOperations.keySet());

    for (Class<?> type : modifiedEntityTypes) {
      // first perform entity UPDATES
      addSortedModificationsForType(type, updates.get(type), flush);
      // next perform entity DELETES
      addSortedModificationsForType(type, deletes.get(type), flush);
      // last perform bulk operations
      SortedSet<DbBulkOperation> bulkOperationsForType = bulkOperations.get(type);
      if(bulkOperationsForType != null) {
        flush.addAll(bulkOperationsForType);
      }
    }

    //the very last perform bulk operations for which the order is important
    if(bulkOperationsInsertionOrder != null) {
      flush.addAll(bulkOperationsInsertionOrder);
    }
  }
274680
private void orderResults(ResultSet cqlRows) throws InvalidRequestException
    {
        if (cqlRows.size() == 0 || !needsPostQueryOrdering())
            return;

        assert orderingIndexes != null;

        List<Integer> idToSort = new ArrayList<Integer>();
        List<Comparator<ByteBuffer>> sorters = new ArrayList<Comparator<ByteBuffer>>();

        for (ColumnIdentifier.Raw identifier : parameters.orderings.keySet())
        {
            ColumnDefinition orderingColumn = cfm.getColumnDefinition(identifier.prepare(cfm));
            idToSort.add(orderingIndexes.get(orderingColumn.name));
            sorters.add(orderingColumn.type);
        }

        Comparator<List<ByteBuffer>> comparator = idToSort.size() == 1
                                                ? new SingleColumnComparator(idToSort.get(0), sorters.get(0))
                                                : new CompositeComparator(sorters, idToSort);
        Collections.sort(cqlRows.rows, comparator);
    }
1352925
def _get_order_by(order, orderby, order_by_fields):
    
    try:
        # Find the actual database fieldnames for the keyword.
        db_fieldnames = order_by_fields[orderby]
    except KeyError:
        raise ValueError("Invalid value for 'orderby': '{0}', supported values are: {1}".format(orderby, ', '.join(sorted(order_by_fields.keys()))))

    # Default to descending for some fields, otherwise be ascending
    is_desc = (not order and orderby in ORDER_BY_DESC) \
        or (order or 'asc').lower() in ('desc', 'descending')

    if is_desc:
        return map(lambda name: '-' + name, db_fieldnames)
    else:
        return db_fieldnames
457762
def save(self, *args, **kwargs):
        
        if self._order is None:
            lookup = self.with_respect_to()
            lookup["_order__isnull"] = False
            concrete_model = base_concrete_model(Orderable, self)
            self._order = concrete_model.objects.filter(**lookup).count()
        super(Orderable, self).save(*args, **kwargs)
1012075
def perform_index_validation(self, data):
        
        # Build a list of dict containing query values for each unique index.
        index_data = []
        for columns, unique in self.instance._meta.indexes:
            if not unique:
                continue
            index_data.append({col: data.get(col, None) for col in columns})

        # Then query for each unique index to see if the value is unique.
        for index in index_data:
            query = self.instance.filter(**index)
            # If we have a primary key, need to exclude the current record from the check.
            if self.pk_field and self.pk_value:
                query = query.where(~(self.pk_field == self.pk_value))
            if query.count():
                err = ValidationError('index', fields=str.join(', ', index.keys()))
                for col in index.keys():
                    self.add_error(col, err)
1285117
def _ordered_iterator(self):
        
        # A list of tuples, each with:
        #   * The iterable
        #   * The QuerySet number
        #   * The next value
        #
        # (Remember that each QuerySet is already sorted.)
        iterables = []
        for i, qs in zip(self._queryset_idxs, self._querysets):
            it = iter(qs)
            try:
                value = next(it)
            except StopIteration:
                # If this is already empty, just skip it.
                continue
            # Set the QuerySet number so that the comparison works properly.
            setattr(value, '#', i)
            iterables.append((it, i, value))

        # The offset of items returned.
        index = 0

        # Create a comparison function based on the requested ordering.
        _comparator = self._generate_comparator(self._order_by)
        def comparator(tuple_1, tuple_2):
            # The last element in each tuple is the actual item to compare.
            return _comparator(tuple_1[2], tuple_2[2])
        comparator = functools.cmp_to_key(comparator)

        # If in reverse mode, get the last value instead of the first value from
        # ordered_values below.
        if self._standard_ordering:
            next_value_ind = 0
        else:
            next_value_ind = -1

        # Continue until all iterables are empty.
        while iterables:
            # If there's only one iterator left, don't bother sorting.
            if len(iterables) > 1:
                # Sort the current values for each iterable.
                iterables = sorted(iterables, key=comparator)

                # The next ordering item is in the first position, unless we're
                # in reverse mode.
                it, i, value = iterables[next_value_ind]
            else:
                it, i, value = iterables[0]

            # Return the next value if we're within the slice of interest.
            if self._low_mark <= index:
                yield value
            index += 1
            # We've left the slice of interest, we're done.
            if index == self._high_mark:
                return

            # Iterate the iterable that just lost a value.
            try:
                value = next(it)
                # Set the QuerySet number so that the comparison works properly.
                setattr(value, '#', i)
                iterables[next_value_ind] = it, i, value
            except StopIteration:
                # This iterator is done, remove it.
                del iterables[next_value_ind]
291853
def as_ordered(self, inplace=False):
        
        inplace = validate_bool_kwarg(inplace, 'inplace')
        return self.set_ordered(True, inplace=inplace)
1226286
def order_by(self, order_attribute):
        '''  '''
        to_return = []
        for f in sorted(self.items, key=lambda i: getattr(i, order_attribute)):
            to_return.append(f)
        return to_return
437464
def insert(self, index, key, value):
        """"""
        if key in self.keyOrder:
            n = self.keyOrder.index(key)
            del self.keyOrder[n]
            if n < index:
                index -= 1
        self.keyOrder.insert(index, key)
        super(SortedDict, self).__setitem__(key, value)
134219
def order_by_position(qs, reverse=False):
    """"""
    if qs:
        # ATTENTION: Django creates an invalid sql statement if two related
        # models have both generic positions, so we cannot use
        # qs.oder_by('generic_position__position')
        position = 'position'
        if reverse:
            position = '-' + position
        # Get content type of first queryset item
        c_type = ContentType.objects.get_for_model(qs[0])
        # Check that every item has a valid position item
        for obj in qs:
            ObjectPosition.objects.get_or_create(
                content_type=c_type, object_id=obj.pk)
        return [
            o.content_object for o in ObjectPosition.objects.filter(
                content_type=c_type, object_id__in=qs).order_by(position)
        ]
    return qs
1147745
def sort(self, *sort_tuples):
        ''' 
        '''
        query = self
        for name, direction in sort_tuples:
            field = resolve_name(self.type, name)
            if direction in (ASCENDING, 1):
                query = query.ascending(field)
            elif direction in (DESCENDING, -1):
                query = query.descending(field)
            else:
                raise BadQueryException('Bad sort direction: %s' % direction)
        return query