Python django.db.models.sql.query.Query() Examples

The following are code examples for showing how to use django.db.models.sql.query.Query(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: django-cte-forest   Author: matthiask   File: query.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, model=None, query=None, using=None, offset=None, hints=None):
        """
        Prepares a CTEQuery object by adding appropriate extras, namely the
        SELECT virtual fields, the WHERE clause which matches the CTE pk with
        the real table pk, and the tree-specific order_by parameters. If the
        query object has already been prepared through this phase, then it
        won't be prepared again.

        :param model:
        :type model:
        :param query:
        :type query:
        :param using:
        :type using:
        :param offset:
        :type offset:
        :return:
        :rtype:
        """
        # Only create an instance of a Query if this is the first invocation in
        # a query chain.
        if query is None:
            query = CTEQuery(model, offset=offset)
        super(CTEQuerySet, self).__init__(model, query, using) 
Example 2
Project: django-cte-forest   Author: matthiask   File: query.py    (license) View Source Project 6 votes vote down vote up
def get_compiler(self, using=None, connection=None):
        """ Overrides the Query method get_compiler in order to return
            an instance of the above custom compiler.
        """
        # Copy the body of this method from Django except the final
        # return statement. We will ignore code coverage for this.
        if using is None and connection is None:  # pragma: no cover
            raise ValueError("Need either using or connection")
        if using:
            connection = connections[using]
        # Check that the compiler will be able to execute the query
        for alias, aggregate in self.annotation_select.items():
            connection.ops.check_expression_support(aggregate)
        # Instantiate the custom compiler.
        return {
            CTEUpdateQuery: CTEUpdateQueryCompiler,
            CTEInsertQuery: CTEInsertQueryCompiler,
            CTEDeleteQuery: CTEDeleteQueryCompiler,
            CTEAggregateQuery: CTEAggregateQueryCompiler,
        }.get(self.__class__, CTEQueryCompiler)(self, connection, using) 
Example 3
Project: django-querysetsequence   Author: percipient   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, *args):
        self._querysets = list(args)
        # Mark each QuerySet's Model with the number of the QuerySet it is.
        for i, qs in enumerate(self._querysets):
            # Generate a Proxy model and then modify that to allow for the same
            # Model to be used in multiple QuerySetSequences at once.
            qs.model = self._get_model(qs.model)
            # Also push this to the Query object since that holds it's own
            # reference to QuerySet.model instead of asking the QuerySet for it.
            qs.query.model = qs.model

            # Actually set the attribute.
            setattr(qs.model, '#', i)

        # Call super to pick up a variety of properties.
        super(QuerySequence, self).__init__(model=None) 
Example 4
Project: Scrum   Author: prakharchoudhary   File: lookups.py    (license) View Source Project 5 votes vote down vote up
def process_rhs(self, compiler, connection):
        if isinstance(self.rhs, Query):
            # If rhs is some Query, don't touch it.
            return super(GISLookup, self).process_rhs(compiler, connection)

        geom = self.rhs
        if isinstance(self.rhs, Col):
            # Make sure the F Expression destination field exists, and
            # set an `srid` attribute with the same as that of the
            # destination.
            geo_fld = self.rhs.output_field
            if not hasattr(geo_fld, 'srid'):
                raise ValueError('No geographic field found in expression.')
            self.rhs.srid = geo_fld.srid
        elif isinstance(self.rhs, Expression):
            raise ValueError('Complex expressions not supported for spatial fields.')
        elif isinstance(self.rhs, (list, tuple)):
            geom = self.rhs[0]
            # Check if a band index was passed in the query argument.
            if ((len(self.rhs) == 2 and not self.lookup_name == 'relate') or
                    (len(self.rhs) == 3 and self.lookup_name == 'relate')):
                self.process_band_indices()
            elif len(self.rhs) > 2:
                raise ValueError('Tuple too long for lookup %s.' % self.lookup_name)
        elif isinstance(self.lhs, RasterBandTransform):
            self.process_band_indices(only_lhs=True)

        rhs, rhs_params = super(GISLookup, self).process_rhs(compiler, connection)
        rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, geom, compiler)
        return rhs, rhs_params 
Example 5
Project: django   Author: alexsukhrin   File: lookups.py    (license) View Source Project 5 votes vote down vote up
def process_rhs(self, compiler, connection):
        if isinstance(self.rhs, Query):
            # If rhs is some Query, don't touch it.
            return super(GISLookup, self).process_rhs(compiler, connection)

        geom = self.rhs
        if isinstance(self.rhs, Col):
            # Make sure the F Expression destination field exists, and
            # set an `srid` attribute with the same as that of the
            # destination.
            geo_fld = self.rhs.output_field
            if not hasattr(geo_fld, 'srid'):
                raise ValueError('No geographic field found in expression.')
            self.rhs.srid = geo_fld.srid
        elif isinstance(self.rhs, Expression):
            raise ValueError('Complex expressions not supported for spatial fields.')
        elif isinstance(self.rhs, (list, tuple)):
            geom = self.rhs[0]
            # Check if a band index was passed in the query argument.
            if ((len(self.rhs) == 2 and not self.lookup_name == 'relate') or
                    (len(self.rhs) == 3 and self.lookup_name == 'relate')):
                self.process_band_indices()
            elif len(self.rhs) > 2:
                raise ValueError('Tuple too long for lookup %s.' % self.lookup_name)
        elif isinstance(self.lhs, RasterBandTransform):
            self.process_band_indices(only_lhs=True)

        rhs, rhs_params = super(GISLookup, self).process_rhs(compiler, connection)
        rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, geom, compiler)
        return rhs, rhs_params 
Example 6
Project: django-cte-forest   Author: matthiask   File: query.py    (license) View Source Project 5 votes vote down vote up
def clone(self, klass=None, memo=None, **kwargs):
            """ Overrides Django's Query clone in order to return appropriate CTE
                compiler based on the target Query class. This mechanism is used by
                methods such as 'update' and '_update' in order to generate UPDATE
                queries rather than SELECT queries.
            """
            klass = {
                UpdateQuery: CTEUpdateQuery,
                InsertQuery: CTEInsertQuery,
                DeleteQuery: CTEDeleteQuery,
                AggregateQuery: CTEAggregateQuery,
            }.get(klass, self.__class__)
            return super(CTEQuery, self).clone(klass, memo, **kwargs) 
Example 7
Project: django-cte-forest   Author: matthiask   File: query.py    (license) View Source Project 5 votes vote down vote up
def chain(self, klass=None):
            """ Overrides Django's Query clone in order to return appropriate CTE
                compiler based on the target Query class. This mechanism is used by
                methods such as 'update' and '_update' in order to generate UPDATE
                queries rather than SELECT queries.
            """
            klass = {
                UpdateQuery: CTEUpdateQuery,
                InsertQuery: CTEInsertQuery,
                DeleteQuery: CTEDeleteQuery,
                AggregateQuery: CTEAggregateQuery,
            }.get(klass, self.__class__)
            return super(CTEQuery, self).chain(klass) 
Example 8
Project: django-querysetsequence   Author: percipient   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def cumsum(seq):
    s = 0
    for c in seq:
        s += c
        yield s


# Bridge the Django >= 1.11 Iterable object back to the Query object being an
# iterator. 
Example 9
Project: liberator   Author: libscie   File: lookups.py    (license) View Source Project 5 votes vote down vote up
def process_rhs(self, compiler, connection):
        if isinstance(self.rhs, Query):
            # If rhs is some Query, don't touch it.
            return super(GISLookup, self).process_rhs(compiler, connection)

        geom = self.rhs
        if isinstance(self.rhs, Col):
            # Make sure the F Expression destination field exists, and
            # set an `srid` attribute with the same as that of the
            # destination.
            geo_fld = self.rhs.output_field
            if not hasattr(geo_fld, 'srid'):
                raise ValueError('No geographic field found in expression.')
            self.rhs.srid = geo_fld.srid
        elif isinstance(self.rhs, Expression):
            raise ValueError('Complex expressions not supported for spatial fields.')
        elif isinstance(self.rhs, (list, tuple)):
            geom = self.rhs[0]
            # Check if a band index was passed in the query argument.
            if ((len(self.rhs) == 2 and not self.lookup_name == 'relate') or
                    (len(self.rhs) == 3 and self.lookup_name == 'relate')):
                self.process_band_indices()
            elif len(self.rhs) > 2:
                raise ValueError('Tuple too long for lookup %s.' % self.lookup_name)
        elif isinstance(self.lhs, RasterBandTransform):
            self.process_band_indices(only_lhs=True)

        rhs, rhs_params = super(GISLookup, self).process_rhs(compiler, connection)
        rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, geom, compiler)
        return rhs, rhs_params 
Example 10
Project: django-rtc   Author: scifiswapnil   File: lookups.py    (license) View Source Project 5 votes vote down vote up
def process_rhs(self, compiler, connection):
        if isinstance(self.rhs, Query):
            # If rhs is some Query, don't touch it.
            return super(GISLookup, self).process_rhs(compiler, connection)

        geom = self.rhs
        if isinstance(self.rhs, Col):
            # Make sure the F Expression destination field exists, and
            # set an `srid` attribute with the same as that of the
            # destination.
            geo_fld = self.rhs.output_field
            if not hasattr(geo_fld, 'srid'):
                raise ValueError('No geographic field found in expression.')
            self.rhs.srid = geo_fld.srid
        elif isinstance(self.rhs, Expression):
            raise ValueError('Complex expressions not supported for spatial fields.')
        elif isinstance(self.rhs, (list, tuple)):
            geom = self.rhs[0]
            # Check if a band index was passed in the query argument.
            if ((len(self.rhs) == 2 and not self.lookup_name == 'relate') or
                    (len(self.rhs) == 3 and self.lookup_name == 'relate')):
                self.process_band_indices()
            elif len(self.rhs) > 2:
                raise ValueError('Tuple too long for lookup %s.' % self.lookup_name)
        elif isinstance(self.lhs, RasterBandTransform):
            self.process_band_indices(only_lhs=True)

        rhs, rhs_params = super(GISLookup, self).process_rhs(compiler, connection)
        rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, geom, compiler)
        return rhs, rhs_params 
Example 11
Project: LatinSounds_AppEnviaMail   Author: G3ek-aR   File: lookups.py    (license) View Source Project 5 votes vote down vote up
def process_rhs(self, compiler, connection):
        if isinstance(self.rhs, Query):
            # If rhs is some Query, don't touch it.
            return super(GISLookup, self).process_rhs(compiler, connection)

        geom = self.rhs
        if isinstance(self.rhs, Col):
            # Make sure the F Expression destination field exists, and
            # set an `srid` attribute with the same as that of the
            # destination.
            geo_fld = self.rhs.output_field
            if not hasattr(geo_fld, 'srid'):
                raise ValueError('No geographic field found in expression.')
            self.rhs.srid = geo_fld.srid
        elif isinstance(self.rhs, Expression):
            raise ValueError('Complex expressions not supported for spatial fields.')
        elif isinstance(self.rhs, (list, tuple)):
            geom = self.rhs[0]
            # Check if a band index was passed in the query argument.
            if ((len(self.rhs) == 2 and not self.lookup_name == 'relate') or
                    (len(self.rhs) == 3 and self.lookup_name == 'relate')):
                self.process_band_indices()
            elif len(self.rhs) > 2:
                raise ValueError('Tuple too long for lookup %s.' % self.lookup_name)
        elif isinstance(self.lhs, RasterBandTransform):
            self.process_band_indices(only_lhs=True)

        rhs, rhs_params = super(GISLookup, self).process_rhs(compiler, connection)
        rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, geom, compiler)
        return rhs, rhs_params 
Example 12
Project: CodingDojo   Author: ComputerSocietyUNB   File: compiler.py    (license) View Source Project 4 votes vote down vote up
def pre_sql_setup(self):
        """
        If the update depends on results from other tables, we need to do some
        munging of the "where" conditions to match the format required for
        (portable) SQL updates. That is done here.

        Further, if we are going to be running multiple updates, we pull out
        the id values to update at this point so that they don't change as a
        result of the progressive updates.
        """
        refcounts_before = self.query.alias_refcount.copy()
        # Ensure base table is in the query
        self.query.get_initial_alias()
        count = self.query.count_active_tables()
        if not self.query.related_updates and count == 1:
            return
        query = self.query.clone(klass=Query)
        query.select_related = False
        query.clear_ordering(True)
        query._extra = {}
        query.select = []
        query.add_fields([query.get_meta().pk.name])
        super(SQLUpdateCompiler, self).pre_sql_setup()

        must_pre_select = count > 1 and not self.connection.features.update_can_self_select

        # Now we adjust the current query: reset the where clause and get rid
        # of all the tables we don't need (since they're in the sub-select).
        self.query.where = self.query.where_class()
        if self.query.related_updates or must_pre_select:
            # Either we're using the idents in multiple update queries (so
            # don't want them to change), or the db backend doesn't support
            # selecting from the updating table (e.g. MySQL).
            idents = []
            for rows in query.get_compiler(self.using).execute_sql(MULTI):
                idents.extend(r[0] for r in rows)
            self.query.add_filter(('pk__in', idents))
            self.query.related_ids = idents
        else:
            # The fast path. Filters and updates in one query.
            self.query.add_filter(('pk__in', query))
        self.query.reset_refcounts(refcounts_before) 
Example 13
Project: lifesoundtrack   Author: MTG   File: compiler.py    (license) View Source Project 4 votes vote down vote up
def pre_sql_setup(self):
        """
        If the update depends on results from other tables, we need to do some
        munging of the "where" conditions to match the format required for
        (portable) SQL updates. That is done here.

        Further, if we are going to be running multiple updates, we pull out
        the id values to update at this point so that they don't change as a
        result of the progressive updates.
        """
        refcounts_before = self.query.alias_refcount.copy()
        # Ensure base table is in the query
        self.query.get_initial_alias()
        count = self.query.count_active_tables()
        if not self.query.related_updates and count == 1:
            return
        query = self.query.clone(klass=Query)
        query.select_related = False
        query.clear_ordering(True)
        query._extra = {}
        query.select = []
        query.add_fields([query.get_meta().pk.name])
        super(SQLUpdateCompiler, self).pre_sql_setup()

        must_pre_select = count > 1 and not self.connection.features.update_can_self_select

        # Now we adjust the current query: reset the where clause and get rid
        # of all the tables we don't need (since they're in the sub-select).
        self.query.where = self.query.where_class()
        if self.query.related_updates or must_pre_select:
            # Either we're using the idents in multiple update queries (so
            # don't want them to change), or the db backend doesn't support
            # selecting from the updating table (e.g. MySQL).
            idents = []
            for rows in query.get_compiler(self.using).execute_sql(MULTI):
                idents.extend(r[0] for r in rows)
            self.query.add_filter(('pk__in', idents))
            self.query.related_ids = idents
        else:
            # The fast path. Filters and updates in one query.
            self.query.add_filter(('pk__in', query))
        self.query.reset_refcounts(refcounts_before) 
Example 14
Project: liberator   Author: libscie   File: compiler.py    (license) View Source Project 4 votes vote down vote up
def pre_sql_setup(self):
        """
        If the update depends on results from other tables, we need to do some
        munging of the "where" conditions to match the format required for
        (portable) SQL updates. That is done here.

        Further, if we are going to be running multiple updates, we pull out
        the id values to update at this point so that they don't change as a
        result of the progressive updates.
        """
        refcounts_before = self.query.alias_refcount.copy()
        # Ensure base table is in the query
        self.query.get_initial_alias()
        count = self.query.count_active_tables()
        if not self.query.related_updates and count == 1:
            return
        query = self.query.clone(klass=Query)
        query.select_related = False
        query.clear_ordering(True)
        query._extra = {}
        query.select = []
        query.add_fields([query.get_meta().pk.name])
        super(SQLUpdateCompiler, self).pre_sql_setup()

        must_pre_select = count > 1 and not self.connection.features.update_can_self_select

        # Now we adjust the current query: reset the where clause and get rid
        # of all the tables we don't need (since they're in the sub-select).
        self.query.where = self.query.where_class()
        if self.query.related_updates or must_pre_select:
            # Either we're using the idents in multiple update queries (so
            # don't want them to change), or the db backend doesn't support
            # selecting from the updating table (e.g. MySQL).
            idents = []
            for rows in query.get_compiler(self.using).execute_sql(MULTI):
                idents.extend(r[0] for r in rows)
            self.query.add_filter(('pk__in', idents))
            self.query.related_ids = idents
        else:
            # The fast path. Filters and updates in one query.
            self.query.add_filter(('pk__in', query))
        self.query.reset_refcounts(refcounts_before) 
Example 15
Project: djanoDoc   Author: JustinChavez   File: compiler.py    (license) View Source Project 4 votes vote down vote up
def pre_sql_setup(self):
        """
        If the update depends on results from other tables, we need to do some
        munging of the "where" conditions to match the format required for
        (portable) SQL updates. That is done here.

        Further, if we are going to be running multiple updates, we pull out
        the id values to update at this point so that they don't change as a
        result of the progressive updates.
        """
        refcounts_before = self.query.alias_refcount.copy()
        # Ensure base table is in the query
        self.query.get_initial_alias()
        count = self.query.count_active_tables()
        if not self.query.related_updates and count == 1:
            return
        query = self.query.clone(klass=Query)
        query.select_related = False
        query.clear_ordering(True)
        query._extra = {}
        query.select = []
        query.add_fields([query.get_meta().pk.name])
        super(SQLUpdateCompiler, self).pre_sql_setup()

        must_pre_select = count > 1 and not self.connection.features.update_can_self_select

        # Now we adjust the current query: reset the where clause and get rid
        # of all the tables we don't need (since they're in the sub-select).
        self.query.where = self.query.where_class()
        if self.query.related_updates or must_pre_select:
            # Either we're using the idents in multiple update queries (so
            # don't want them to change), or the db backend doesn't support
            # selecting from the updating table (e.g. MySQL).
            idents = []
            for rows in query.get_compiler(self.using).execute_sql(MULTI):
                idents.extend(r[0] for r in rows)
            self.query.add_filter(('pk__in', idents))
            self.query.related_ids = idents
        else:
            # The fast path. Filters and updates in one query.
            self.query.add_filter(('pk__in', query))
        self.query.reset_refcounts(refcounts_before) 
Example 16
Project: django-next-train   Author: bitpixdigital   File: compiler.py    (license) View Source Project 4 votes vote down vote up
def pre_sql_setup(self):
        """
        If the update depends on results from other tables, we need to do some
        munging of the "where" conditions to match the format required for
        (portable) SQL updates. That is done here.

        Further, if we are going to be running multiple updates, we pull out
        the id values to update at this point so that they don't change as a
        result of the progressive updates.
        """
        refcounts_before = self.query.alias_refcount.copy()
        # Ensure base table is in the query
        self.query.get_initial_alias()
        count = self.query.count_active_tables()
        if not self.query.related_updates and count == 1:
            return
        query = self.query.clone(klass=Query)
        query.select_related = False
        query.clear_ordering(True)
        query._extra = {}
        query.select = []
        query.add_fields([query.get_meta().pk.name])
        super(SQLUpdateCompiler, self).pre_sql_setup()

        must_pre_select = count > 1 and not self.connection.features.update_can_self_select

        # Now we adjust the current query: reset the where clause and get rid
        # of all the tables we don't need (since they're in the sub-select).
        self.query.where = self.query.where_class()
        if self.query.related_updates or must_pre_select:
            # Either we're using the idents in multiple update queries (so
            # don't want them to change), or the db backend doesn't support
            # selecting from the updating table (e.g. MySQL).
            idents = []
            for rows in query.get_compiler(self.using).execute_sql(MULTI):
                idents.extend(r[0] for r in rows)
            self.query.add_filter(('pk__in', idents))
            self.query.related_ids = idents
        else:
            # The fast path. Filters and updates in one query.
            self.query.add_filter(('pk__in', query))
        self.query.reset_refcounts(refcounts_before) 
Example 17
Project: LatinSounds_AppEnviaMail   Author: G3ek-aR   File: compiler.py    (license) View Source Project 4 votes vote down vote up
def pre_sql_setup(self):
        """
        If the update depends on results from other tables, we need to do some
        munging of the "where" conditions to match the format required for
        (portable) SQL updates. That is done here.

        Further, if we are going to be running multiple updates, we pull out
        the id values to update at this point so that they don't change as a
        result of the progressive updates.
        """
        refcounts_before = self.query.alias_refcount.copy()
        # Ensure base table is in the query
        self.query.get_initial_alias()
        count = self.query.count_active_tables()
        if not self.query.related_updates and count == 1:
            return
        query = self.query.clone(klass=Query)
        query.select_related = False
        query.clear_ordering(True)
        query._extra = {}
        query.select = []
        query.add_fields([query.get_meta().pk.name])
        super(SQLUpdateCompiler, self).pre_sql_setup()

        must_pre_select = count > 1 and not self.connection.features.update_can_self_select

        # Now we adjust the current query: reset the where clause and get rid
        # of all the tables we don't need (since they're in the sub-select).
        self.query.where = self.query.where_class()
        if self.query.related_updates or must_pre_select:
            # Either we're using the idents in multiple update queries (so
            # don't want them to change), or the db backend doesn't support
            # selecting from the updating table (e.g. MySQL).
            idents = []
            for rows in query.get_compiler(self.using).execute_sql(MULTI):
                idents.extend(r[0] for r in rows)
            self.query.add_filter(('pk__in', idents))
            self.query.related_ids = idents
        else:
            # The fast path. Filters and updates in one query.
            self.query.add_filter(('pk__in', query))
        self.query.reset_refcounts(refcounts_before) 
Example 18
Project: django-wechat-api   Author: crazy-canux   File: compiler.py    (license) View Source Project 4 votes vote down vote up
def pre_sql_setup(self):
        """
        If the update depends on results from other tables, we need to do some
        munging of the "where" conditions to match the format required for
        (portable) SQL updates. That is done here.

        Further, if we are going to be running multiple updates, we pull out
        the id values to update at this point so that they don't change as a
        result of the progressive updates.
        """
        refcounts_before = self.query.alias_refcount.copy()
        # Ensure base table is in the query
        self.query.get_initial_alias()
        count = self.query.count_active_tables()
        if not self.query.related_updates and count == 1:
            return
        query = self.query.clone(klass=Query)
        query.select_related = False
        query.clear_ordering(True)
        query._extra = {}
        query.select = []
        query.add_fields([query.get_meta().pk.name])
        super(SQLUpdateCompiler, self).pre_sql_setup()

        must_pre_select = count > 1 and not self.connection.features.update_can_self_select

        # Now we adjust the current query: reset the where clause and get rid
        # of all the tables we don't need (since they're in the sub-select).
        self.query.where = self.query.where_class()
        if self.query.related_updates or must_pre_select:
            # Either we're using the idents in multiple update queries (so
            # don't want them to change), or the db backend doesn't support
            # selecting from the updating table (e.g. MySQL).
            idents = []
            for rows in query.get_compiler(self.using).execute_sql(MULTI):
                idents.extend(r[0] for r in rows)
            self.query.add_filter(('pk__in', idents))
            self.query.related_ids = idents
        else:
            # The fast path. Filters and updates in one query.
            self.query.add_filter(('pk__in', query))
        self.query.reset_refcounts(refcounts_before)