Create order items for objects already present in the database.
495598
def create_order_objects(model, order_fields):
    
    for rel in model._meta.get_all_related_objects():
        rel_model = rel.model
        if rel_model.__module__ == 'order.models':

            objs = model.objects.all()
            values = {}
            for order_field in order_fields:
                order_objs = rel_model.objects.all().order_by('-%s' \
                        % order_field)
                try:
                    values[order_field] = getattr(order_objs[0], \
                            order_field) + 1
                except IndexError:
                    values[order_field] = 1
            for obj in objs:
                try:
                    rel_model.objects.get(item=obj)
                except rel_model.DoesNotExist:
                    rel_model.objects.create(item=obj, **values)
                    for key in values:
                        values[key] += 1
1200853
def insert_with_id(obj):
    
    if '_id' in obj:
        raise ValueError("object already has '_id' field")

    # add created_at/updated_at on insert
    obj['created_at'] = datetime.datetime.utcnow()
    obj['updated_at'] = obj['created_at']

    if obj['_type'] == 'person' or obj['_type'] == 'legislator':
        collection = db.legislators
        id_type = 'L'
    elif obj['_type'] == 'committee':
        collection = db.committees
        id_type = 'C'
    elif obj['_type'] == 'bill':
        collection = db.bills
        id_type = 'B'
    else:
        raise ValueError("unknown _type for object")

    # get abbr
    abbr = obj[settings.LEVEL_FIELD].upper()

    id_reg = re.compile('^%s%s' % (abbr, id_type))

    # Find the next available _id and insert
    id_prefix = '%s%s' % (abbr, id_type)
    cursor = collection.find({'_id': id_reg}).sort('_id', -1).limit(1)

    try:
        new_id = int(next(cursor)['_id'][len(abbr) + 1:]) + 1
    except StopIteration:
        new_id = 1

    while True:
        if obj['_type'] == 'bill':
            obj['_id'] = '%s%08d' % (id_prefix, new_id)
        else:
            obj['_id'] = '%s%06d' % (id_prefix, new_id)
        obj['_all_ids'] = [obj['_id']]

        if obj['_type'] in ['person', 'legislator']:
            obj['leg_id'] = obj['_id']

        try:
            return collection.insert(obj, safe=True)
        except pymongo.errors.DuplicateKeyError:
            new_id += 1
988444
public function reorder()
    {
        $store = $this->getRepository()->getStore();
        $query = $this->getScopedQuery($this->_mixer);
        $store->execute('SET @order = 0');
        $query->update('@col(ordering) = (@order := @order + 1)')->order('ordering', 'ASC');
        $store->execute($query);
    }
510306
def _prepare_order_bys(self):
        
        order_bys = OrderedSet()
        if self._order_bys:
            for ingredient in self._order_bys:
                if isinstance(ingredient, Dimension):
                    # Reverse the ordering columns so that dimensions
                    # order by their label rather than their id
                    columns = reversed(ingredient.columns)
                else:
                    columns = ingredient.columns
                for c in columns:
                    order_by = c.desc() if ingredient.ordering == 'desc' else c
                    if str(order_by) not in [str(o) for o in order_bys]:
                        order_bys.add(order_by)

        return list(order_bys)
1230976
def order_items(params={})
      order_items = get("/orders/#{id}/order_items")
      if order_items
        order_items["order_items"].map { |data| FetchAppAPI::OrderItem.new(data) }
      end
    end
140859
def order_by(self, **kwargs):
        
        if kwargs:
            col, order = kwargs.popitem()
            self.order_clause = "order by {col} {order} ".format(
                col=col, order=order)
        return self
429692
def save(self, *args, **kwargs):
        """"""
        objects = self.get_filtered_manager()
        old_pos = getattr(self, '_original_sort_order', None)
        new_pos = self.sort_order

        if old_pos is None and self._unique_togethers_changed():
            self.sort_order = None
            new_pos = None

        try:
            with transaction.atomic():
                self._save(objects, old_pos, new_pos)
        except IntegrityError:
            with transaction.atomic():
                old_pos = objects.filter(pk=self.pk).values_list(
                    'sort_order', flat=True)[0]
                self._save(objects, old_pos, new_pos)

        # Call the "real" save() method.
        super(Orderable, self).save(*args, **kwargs)
776290
def create_checkout_order(self, checkout_id, **params):
        """"""
        response = self._post('v2', 'checkouts', checkout_id, 'orders', data=params)
        return self._make_api_object(response, Order)
1219809
def order_by_raw(self, sql, bindings=None):
        
        if bindings is None:
            bindings = []

        type = "raw"

        self.orders.append({"type": type, "sql": sql})

        self.add_binding(bindings, "order")

        return self
869059
function createIndexes() {
            // create listed indexes if they don't already exist.
            return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) {
                var entity = CRUD.EntityManager.entities[entityName];
                if (('indexes' in entity)) {
                    return Promise.all(entity.indexes.map(function(index) {
                        var indexName = index.replace(/\W/g, '') + '_idx';
                        if (!(entity.table in indexes) || indexes[entity.table].indexOf(indexName) == -1) {
                            return db.execute("create index if not exists " + indexName + " on " + entity.table + " (" + index + ")").then(function(result) {
                                CRUD.log("index created: ", entity.table, index, indexName);
                                if (!(entity.table in indexes)) {
                                    indexes[entity.table] = [];
                                }
                                indexes[entity.table].push(indexName);
                                return;
                            });
                        }
                        return;
                    }));
                }
            }));
        }
786883
def create_new_database(request):
    """"""
    name = "Create a New MongoDB Database"

    if request.method == 'POST':
        form = CreateDatabaseForm(request.POST)

        if form.is_valid():
            result = form.save()
            if "error" in result:
                messages.error(
                    request, "The database creation operation failed.")
                messages.error(request, result["error"])
            else:
                messages.success(request, "Database created.")
            return HttpResponseRedirect(reverse('djmongo_show_dbs'))
        else:
            # The form is invalid
            messages.error(
                request, _("Please correct the errors in the form."))
            return render(request,
                          'djmongo/console/generic/bootstrapform.html',
                          {'form': form,
                           'name': name})

    else:
        # this is a GET
        context = {'name': name,
                   'form': CreateDatabaseForm(
                       initial={"initial_document": '{ "foo" : "bar" }'
                                })
                   }
        return render(request, 'djmongo/console/generic/bootstrapform.html',
                      context)
60954
def _create_options(self, items):
        
        return OrderedDict(map(lambda x: (x.name, x),
                           coerce_to_list(items, self.preprocess)))
1002356
def _create(cls, model_class, *args, **kwargs):
        """"""
        session = cls._meta.sqlalchemy_session
        session_persistence = cls._meta.sqlalchemy_session_persistence
        if cls._meta.force_flush:
            session_persistence = SESSION_PERSISTENCE_FLUSH

        obj = model_class(*args, **kwargs)
        if session is None:
            raise RuntimeError("No session provided.")
        session.add(obj)
        if session_persistence == SESSION_PERSISTENCE_FLUSH:
            session.flush()
        elif session_persistence == SESSION_PERSISTENCE_COMMIT:
            session.commit()
        return obj
797494
function createOrder()
    {
        // Make order
        $productCollectionID = $this->attribute( 'productcollection_id' );

        $user = eZUser::currentUser();
        $userID = $user->attribute( 'contentobject_id' );

        $time = time();
        $order = new eZOrder( array( 'productcollection_id' => $productCollectionID,
                                     'user_id' => $userID,
                                     'is_temporary' => 1,
                                     'created' => $time,
                                     'status_id' => eZOrderStatus::PENDING,
                                     'status_modified' => $time,
                                     'status_modifier_id' => $userID
                                     ) );

        $db = eZDB::instance();
        $db->begin();
        $order->store();

        $orderID = $order->attribute( 'id' );
        $this->setAttribute( 'order_id', $orderID );
        $this->store();
        $db->commit();

        return $order;
    }
1016436
def _make_order(field_path, direction):
        """"""
        return query_pb2.StructuredQuery.Order(
            field=query_pb2.StructuredQuery.FieldReference(field_path=field_path),
            direction=_enum_from_direction(direction),
        )
453698
private ObjectStore createObjectStore(T id) {
        Validate.notNull(id, "ID must be specified");
        ObjectStore store = createNewObjectStore();
        ObjectStore previousStore = stores.putIfAbsent(id, store);
        if (previousStore != null) {
            return previousStore;
        }
        return store;
    }
766457
protected function createOrder(array $data = null)
    {
        $order = new DatabaseOrder();
        if ($data !== null) {
            $order->setData($data);
        }
        return $order;
    }