def get(cls, expression): """ Retrieve the model instance matching the given expression. If the number of matching results is not equal to one, then a ``ValueError`` will be raised. :param expression: A boolean expression to filter by. :returns: The matching :py:class:`Model` instance. :raises: ``ValueError`` if result set size is not 1. """ executor = Executor(cls.database) result = executor.execute(expression) if len(result) != 1: raise ValueError('Got %s results, expected 1.' % len(result)) return cls.load(result._first_or_any(), convert_key=False)
def query(cls, expression=None, order_by=None): """ Return model instances matching the given expression (if specified). Additionally, matching instances can be returned sorted by field value. Example:: # Get administrators sorted by username. admin_users = User.query( (User.admin == True), order_by=User.username) # List blog entries newest to oldest. entries = Entry.query(order_by=Entry.timestamp.desc()) # Perform a complex filter. values = StatData.query( (StatData.timestamp < datetime.date.today()) & ((StatData.type == 'pv') | (StatData.type == 'cv'))) :param expression: A boolean expression to filter by. :param order_by: A field whose value should be used to sort returned instances. """ if expression is not None: executor = Executor(cls.database) result = executor.execute(expression) else: result = cls._query.all_index() if order_by is not None: desc = False if isinstance(order_by, Desc): desc = True order_by = order_by.node alpha = not isinstance(order_by, _ScalarField) result = cls.database.sort( result.key, by='*->%s' % order_by.name, alpha=alpha, desc=desc) elif isinstance(result, ZSet): result = result.iterator(reverse=True) for hash_id in result: yield cls.load(hash_id, convert_key=False)
def query_delete(cls, expression=None): """ Delete model instances matching the given expression (if specified). If no expression is provided, then all model instances will be deleted. :param expression: A boolean expression to filter by. """ if expression is not None: executor = Executor(cls.database) result = executor.execute(expression) else: result = cls._query.all_index() for hash_id in result: cls.load(hash_id, convert_key=False).delete()
def _search(self, query): expression = parse(query, self) if expression is None: return [(member, 0) for member in self.members] executor = Executor(self.db) return executor.execute(expression)