Example #1
0
def create_functions(models_module, update=True):
    """Create the database functions for a given models module.
    """
    for name, function_cls in vars(models_module).iteritems():
        is_function = (
            isinstance(function_cls, type) and
            issubclass(function_cls, Function) and
            hasattr(function_cls, 'sql'))

        if not is_function:
            continue

        function_name = function_cls._meta.db_table
        fields = tuple(
            ' '.join((n, _get_field_type(f))) for n, f in
            get_fields_by_name(function_cls, '*').iteritems())

        definition = function_cls.sql

        full_name = u'{module}.{cls}'.format(
            module=models_module.__name__,
            cls=name)

        try:
            created = create_function(
                connection, function_name, fields, definition)
        except Exception, exc:
            exc.function_cls = function_cls
            exc.python_name = full_name
            raise
        else:
            yield created, function_cls, full_name
Example #2
0
def realize_deferred_projections(sender, *args, **kwargs):
    """Project any fields which were deferred pending model preparation."""
    app_label = sender._meta.app_label
    model_name = sender.__name__.lower()
    pending = _DEFERRED_PROJECTIONS.pop((app_label, model_name), {})
    for view_cls, field_names in pending.iteritems():
        field_instances = get_fields_by_name(sender, *field_names)
        for name, field in field_instances.iteritems():
            # Only assign the field if the view does not already have an
            # attribute or explicitly-defined field with that name.
            if hasattr(view_cls, name) or hasfield(view_cls, name):
                continue
            copy.copy(field).contribute_to_class(view_cls, name)
Example #3
0
    def call(self, args=None):
        """Prepare the function for filtering by executing it with the
        arguments passed.
        """
        function_name, function_args = self.model._meta.db_table.split(u'(')
        function_args = u'(' + function_args

        model_name = self.model.__name__
        app_label = self.model._meta.app_label
        module = self.model.__module__

        execute_arguments = ''
        if args:
            execute_arguments = ', '.join(unicode(a) for a in args)

        execute_function = u'{name}({args})'.format(
            name=function_name,
            args=execute_arguments)

        fields = get_fields_by_name(self.model, '*')
        model = _create_model(
            model_name, execute_function, fields, app_label, module)
        return models.query.QuerySet(model, query.NonQuotingQuery(model))