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

The following are 17 code examples of django.db.models.sql.Query(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models.sql , or try the search function .
Example #1
Source File: utils.py    From django-cachalot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _find_subqueries_in_where(children):
    for child in children:
        child_class = child.__class__
        if child_class is WhereNode:
            for grand_child in _find_subqueries_in_where(child.children):
                yield grand_child
        elif child_class is ExtraWhere:
            raise IsRawQuery
        elif child_class is NothingNode:
            pass
        else:
            rhs = child.rhs
            rhs_class = rhs.__class__
            if rhs_class is Query:
                yield rhs
            elif rhs_class is QuerySet:
                yield rhs.query
            elif rhs_class is Subquery or rhs_class is Exists:
                try:
                    yield rhs.query
                except:
                    yield rhs.queryset.query
            elif rhs_class in UNCACHABLE_FUNCS:
                raise UncachableQuery 
Example #2
Source File: query.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, model=None, query=None, using=None):
        self.model = model
        # EmptyQuerySet instantiates QuerySet with model as None
        self._db = using
        self.query = query or sql.Query(self.model)
        self._result_cache = None
        self._iter = None
        self._sticky_filter = False
        self._for_write = False
        self._prefetch_related_lookups = []
        self._prefetch_done = False
        self._known_related_objects = {}        # {rel_field, {pk: rel_obj}}

    ########################
    # PYTHON MAGIC METHODS #
    ######################## 
Example #3
Source File: query.py    From python with Apache License 2.0 5 votes vote down vote up
def __init__(self, model=None, query=None, using=None, hints=None):
        self.model = model
        self._db = using
        self._hints = hints or {}
        self.query = query or sql.Query(self.model)
        self._result_cache = None
        self._sticky_filter = False
        self._for_write = False
        self._prefetch_related_lookups = ()
        self._prefetch_done = False
        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}
        self._iterable_class = ModelIterable
        self._fields = None 
Example #4
Source File: query.py    From django-partial-index with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def q_mentioned_fields(q, model):
    """Returns list of field names mentioned in Q object.

    Q(a__isnull=True, b=F('c')) -> ['a', 'b', 'c']
    """
    query = Query(model)
    where = query._add_q(q, used_aliases=set(), allow_joins=False)[0]
    return list(sorted(set(expression_mentioned_fields(where)))) 
Example #5
Source File: query.py    From django-partial-index with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def q_to_sql(q, model, schema_editor):
    # Q -> SQL conversion based on code from Ian Foote's Check Constraints pull request:
    # https://github.com/django/django/pull/7615/

    query = Query(model)
    where = query._add_q(q, used_aliases=set(), allow_joins=False)[0]
    connection = schema_editor.connection
    compiler = connection.ops.compiler('SQLCompiler')(query, connection, 'default')
    sql, params = where.as_sql(compiler, connection)
    params = tuple(map(schema_editor.quote_value, params))
    where_sql = sql % params
    return where_sql 
Example #6
Source File: query.py    From python2017 with MIT License 5 votes vote down vote up
def __iter__(self):
        # Cache some things for performance reasons outside the loop.
        db = self.db
        compiler = connections[db].ops.compiler('SQLCompiler')(
            self.query, connections[db], db
        )

        query = iter(self.query)

        try:
            model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order()

            # Find out which model's fields are not present in the query.
            skip = set()
            for field in self.model._meta.fields:
                if field.attname not in model_init_names:
                    skip.add(field.attname)
            if skip:
                if self.model._meta.pk.attname in skip:
                    raise InvalidQuery('Raw query must include the primary key')
            model_cls = self.model
            fields = [self.model_fields.get(c) for c in self.columns]
            converters = compiler.get_converters([
                f.get_col(f.model._meta.db_table) if f else None for f in fields
            ])
            for values in query:
                if converters:
                    values = compiler.apply_converters(values, converters)
                # Associate fields to values
                model_init_values = [values[pos] for pos in model_init_pos]
                instance = model_cls.from_db(db, model_init_names, model_init_values)
                if annotation_fields:
                    for column, pos in annotation_fields:
                        setattr(instance, column, values[pos])
                yield instance
        finally:
            # Done iterating the Query. If it has its own cursor, close it.
            if hasattr(self.query, 'cursor') and self.query.cursor:
                self.query.cursor.close() 
Example #7
Source File: query.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, model=None, query=None, using=None, hints=None):
        self.model = model
        self._db = using
        self._hints = hints or {}
        self.query = query or sql.Query(self.model)
        self._result_cache = None
        self._sticky_filter = False
        self._for_write = False
        self._prefetch_related_lookups = ()
        self._prefetch_done = False
        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}
        self._iterable_class = ModelIterable
        self._fields = None 
Example #8
Source File: query.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __iter__(self):
        # Cache some things for performance reasons outside the loop.
        db = self.db
        compiler = connections[db].ops.compiler('SQLCompiler')(
            self.query, connections[db], db
        )

        query = iter(self.query)

        try:
            model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order()

            # Find out which model's fields are not present in the query.
            skip = set()
            for field in self.model._meta.fields:
                if field.attname not in model_init_names:
                    skip.add(field.attname)
            if skip:
                if self.model._meta.pk.attname in skip:
                    raise InvalidQuery('Raw query must include the primary key')
                model_cls = deferred_class_factory(self.model, skip)
            else:
                model_cls = self.model
            fields = [self.model_fields.get(c) for c in self.columns]
            converters = compiler.get_converters([
                f.get_col(f.model._meta.db_table) if f else None for f in fields
            ])
            for values in query:
                if converters:
                    values = compiler.apply_converters(values, converters)
                # Associate fields to values
                model_init_values = [values[pos] for pos in model_init_pos]
                instance = model_cls.from_db(db, model_init_names, model_init_values)
                if annotation_fields:
                    for column, pos in annotation_fields:
                        setattr(instance, column, values[pos])
                yield instance
        finally:
            # Done iterating the Query. If it has its own cursor, close it.
            if hasattr(self.query, 'cursor') and self.query.cursor:
                self.query.cursor.close() 
Example #9
Source File: query.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self, model=None, query=None, using=None, hints=None):
        self.model = model
        self._db = using
        self._hints = hints or {}
        self.query = query or sql.Query(self.model)
        self._result_cache = None
        self._sticky_filter = False
        self._for_write = False
        self._prefetch_related_lookups = []
        self._prefetch_done = False
        self._known_related_objects = {}  # {rel_field, {pk: rel_obj}}
        self._iterable_class = ModelIterable
        self._fields = None 
Example #10
Source File: query.py    From python with Apache License 2.0 5 votes vote down vote up
def __iter__(self):
        # Cache some things for performance reasons outside the loop.
        db = self.db
        compiler = connections[db].ops.compiler('SQLCompiler')(
            self.query, connections[db], db
        )

        query = iter(self.query)

        try:
            model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order()

            # Find out which model's fields are not present in the query.
            skip = set()
            for field in self.model._meta.fields:
                if field.attname not in model_init_names:
                    skip.add(field.attname)
            if skip:
                if self.model._meta.pk.attname in skip:
                    raise InvalidQuery('Raw query must include the primary key')
            model_cls = self.model
            fields = [self.model_fields.get(c) for c in self.columns]
            converters = compiler.get_converters([
                f.get_col(f.model._meta.db_table) if f else None for f in fields
            ])
            for values in query:
                if converters:
                    values = compiler.apply_converters(values, converters)
                # Associate fields to values
                model_init_values = [values[pos] for pos in model_init_pos]
                instance = model_cls.from_db(db, model_init_names, model_init_values)
                if annotation_fields:
                    for column, pos in annotation_fields:
                        setattr(instance, column, values[pos])
                yield instance
        finally:
            # Done iterating the Query. If it has its own cursor, close it.
            if hasattr(self.query, 'cursor') and self.query.cursor:
                self.query.cursor.close() 
Example #11
Source File: query.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, model=None, query=None, using=None, hints=None):
        self.model = model
        self._db = using
        self._hints = hints or {}
        self.query = query or sql.Query(self.model)
        self._result_cache = None
        self._sticky_filter = False
        self._for_write = False
        self._prefetch_related_lookups = []
        self._prefetch_done = False
        self._known_related_objects = {}        # {rel_field, {pk: rel_obj}} 
Example #12
Source File: elasticsearch2.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_content_type_filter(self):
        # Query content_type using a "match" query. See comment in
        # Elasticsearch2Mapping.get_document for more details
        content_type = self.mapping_class(self.queryset.model).get_content_type()

        return {
            'match': {
                'content_type': content_type
            }
        } 
Example #13
Source File: query.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def iterator(self):
        # Cache some things for performance reasons outside the loop.
        db = self.db
        compiler = connections[db].ops.compiler('SQLCompiler')(
            self.query, connections[db], db
        )

        query = iter(self.query)

        try:
            model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order()
            if self.model._meta.pk.attname not in model_init_names:
                raise InvalidQuery('Raw query must include the primary key')
            model_cls = self.model
            fields = [self.model_fields.get(c) for c in self.columns]
            converters = compiler.get_converters([
                f.get_col(f.model._meta.db_table) if f else None for f in fields
            ])
            if converters:
                query = compiler.apply_converters(query, converters)
            for values in query:
                # Associate fields to values
                model_init_values = [values[pos] for pos in model_init_pos]
                instance = model_cls.from_db(db, model_init_names, model_init_values)
                if annotation_fields:
                    for column, pos in annotation_fields:
                        setattr(instance, column, values[pos])
                yield instance
        finally:
            # Done iterating the Query. If it has its own cursor, close it.
            if hasattr(self.query, 'cursor') and self.query.cursor:
                self.query.cursor.close() 
Example #14
Source File: query.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def __init__(self, model=None, query=None, using=None, hints=None):
        self.model = model
        self._db = using
        self._hints = hints or {}
        self.query = query or sql.Query(self.model)
        self._result_cache = None
        self._sticky_filter = False
        self._for_write = False
        self._prefetch_related_lookups = ()
        self._prefetch_done = False
        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}
        self._iterable_class = ModelIterable
        self._fields = None 
Example #15
Source File: query.py    From bioforum with MIT License 5 votes vote down vote up
def __iter__(self):
        # Cache some things for performance reasons outside the loop.
        db = self.db
        compiler = connections[db].ops.compiler('SQLCompiler')(
            self.query, connections[db], db
        )

        query = iter(self.query)

        try:
            model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order()
            if self.model._meta.pk.attname not in model_init_names:
                raise InvalidQuery('Raw query must include the primary key')
            model_cls = self.model
            fields = [self.model_fields.get(c) for c in self.columns]
            converters = compiler.get_converters([
                f.get_col(f.model._meta.db_table) if f else None for f in fields
            ])
            if converters:
                query = compiler.apply_converters(query, converters)
            for values in query:
                # Associate fields to values
                model_init_values = [values[pos] for pos in model_init_pos]
                instance = model_cls.from_db(db, model_init_names, model_init_values)
                if annotation_fields:
                    for column, pos in annotation_fields:
                        setattr(instance, column, values[pos])
                yield instance
        finally:
            # Done iterating the Query. If it has its own cursor, close it.
            if hasattr(self.query, 'cursor') and self.query.cursor:
                self.query.cursor.close() 
Example #16
Source File: query.py    From bioforum with MIT License 5 votes vote down vote up
def __init__(self, model=None, query=None, using=None, hints=None):
        self.model = model
        self._db = using
        self._hints = hints or {}
        self.query = query or sql.Query(self.model)
        self._result_cache = None
        self._sticky_filter = False
        self._for_write = False
        self._prefetch_related_lookups = ()
        self._prefetch_done = False
        self._known_related_objects = {}  # {rel_field: {pk: rel_obj}}
        self._iterable_class = ModelIterable
        self._fields = None 
Example #17
Source File: query.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __iter__(self):
        # Cache some things for performance reasons outside the loop.
        db = self.db
        compiler = connections[db].ops.compiler('SQLCompiler')(
            self.query, connections[db], db
        )

        query = iter(self.query)

        try:
            model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order()

            # Find out which model's fields are not present in the query.
            skip = set()
            for field in self.model._meta.fields:
                if field.attname not in model_init_names:
                    skip.add(field.attname)
            if skip:
                if self.model._meta.pk.attname in skip:
                    raise InvalidQuery('Raw query must include the primary key')
                model_cls = deferred_class_factory(self.model, skip)
            else:
                model_cls = self.model
            fields = [self.model_fields.get(c, None) for c in self.columns]
            converters = compiler.get_converters([
                f.get_col(f.model._meta.db_table) if f else None for f in fields
            ])
            for values in query:
                if converters:
                    values = compiler.apply_converters(values, converters)
                # Associate fields to values
                model_init_values = [values[pos] for pos in model_init_pos]
                instance = model_cls.from_db(db, model_init_names, model_init_values)
                if annotation_fields:
                    for column, pos in annotation_fields:
                        setattr(instance, column, values[pos])
                yield instance
        finally:
            # Done iterating the Query. If it has its own cursor, close it.
            if hasattr(self.query, 'cursor') and self.query.cursor:
                self.query.cursor.close()