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

The following are 7 code examples of django.db.models.sql.EmptyResultSet(). 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: caching.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def using_bundle_cache(f, bundle, *args, **kwds):
    """Wraps a function that returns a queryset, and then caches the result in the bundle."""
    queryset = f(bundle, *args, **kwds)
    if hasattr(bundle, '_resource_cache'):
        # The SQL query itself is the key into the cache.
        try:
            # Sometimes this raises EmptyResultSet, so ignore the cache in that case
            # Know Django bug: https://code.djangoproject.com/ticket/22973
            # This occcured when cloning ConfigEntity, the toMany fields of config_entity_resource.py
            # encountered this error. Specifically, I belive it happened with our queries of the
            # toMany relationsip in permission_resource_mixin.py, but it may have been others as well.
            query = str(queryset.query)
        except EmptyResultSet:
            return queryset

        # Return the cached queryset rather than the one we just
        # made, because it has cached results in it.
        if query in bundle._resource_cache:
            bundle._cache_hits[query] += 1
            return bundle._resource_cache[query]

        bundle._resource_cache[query] = queryset
    return queryset 
Example #2
Source File: models.py    From trader with Apache License 2.0 5 votes vote down vote up
def to_df(queryset):
    """
    :param queryset: django.db.models.query.QuerySet
    :return: pandas.core.frame.DataFrame
    """
    try:
        query, params = queryset.query.sql_with_params()
    except EmptyResultSet:
        # Occurs when Django tries to create an expression for a
        # query which will certainly be empty
        # e.g. Book.objects.filter(author__in=[])
        return pd.DataFrame()
    return read_sql_query(query, connection, params=params) 
Example #3
Source File: cache_manager.py    From django-cache-manager with MIT License 5 votes vote down vote up
def iterator(self):
        try:
            key = self.generate_key()
        # workaround for Django bug # 12717
        except EmptyResultSet:
            return
        result_set = self.cache_backend.get(key)
        if result_set is None:
            logger.debug('cache miss for key {0}'.format(key))
            result_set = list(super(CachingQuerySet, self).iterator())
            self.cache_backend.set(key, result_set)
        for result in result_set:
            yield result 
Example #4
Source File: model_integration_tests.py    From django-cache-manager with MIT License 5 votes vote down vote up
def test_empty_list_on_filter_in(self):
        """
        A filter call with __in being passed an empty list should correctly
        handle the EmptyResultSet exception and return None.
        """
        self.assertEqual([], list(Car.objects.filter(make__in=[]))) 
Example #5
Source File: cache_manager_tests.py    From django-cache-manager with MIT License 5 votes vote down vote up
def test_catch_empty_result_set(self, mock_generate_key, mock_cache_backend, invalidate_model_cache):
        """
        When an EmptyResultSet exception is raised in the process
        of passing an empty iterable to an __in parameter, CacheManager
        should correctly handle it and return None.
        """
        mock_generate_key.side_effect = EmptyResultSet()
        manufacturers = Manufacturer.objects.filter(name__in=[])
        self.assertEqual([], list(manufacturers)) 
Example #6
Source File: sql.py    From django-silk with MIT License 5 votes vote down vote up
def execute_sql(self, *args, **kwargs):
    """wrapper around real execute_sql in order to extract information"""

    try:
        q, params = self.as_sql()
        if not q:
            raise EmptyResultSet
    except EmptyResultSet:
        try:
            result_type = args[0]
        except IndexError:
            result_type = kwargs.get('result_type', 'multi')
        if result_type == 'multi':
            return iter([])
        else:
            return
    tb = ''.join(reversed(traceback.format_stack()))
    sql_query = q % params
    if _should_wrap(sql_query):
        query_dict = {
            'query': sql_query,
            'start_time': timezone.now(),
            'traceback': tb
        }
        try:
            return self._execute_sql(*args, **kwargs)
        finally:
            query_dict['end_time'] = timezone.now()
            request = DataCollector().request
            if request:
                query_dict['request'] = request
            if self.query.model.__module__ != 'silk.models':
                DataCollector().register_query(query_dict)
            else:
                DataCollector().register_silk_query(query_dict)
    return self._execute_sql(*args, **kwargs) 
Example #7
Source File: sql.py    From django-silk with MIT License 5 votes vote down vote up
def execute_sql(self, *args, **kwargs):
    """wrapper around real execute_sql in order to extract information"""

    try:
        q, params = self.as_sql()
        if not q:
            raise EmptyResultSet
    except EmptyResultSet:
        try:
            result_type = args[0]
        except IndexError:
            result_type = kwargs.get('result_type', 'multi')
        if result_type == 'multi':
            return iter([])
        else:
            return
    tb = ''.join(reversed(traceback.format_stack()))
    sql_query = q % params
    if _should_wrap(sql_query):
        query_dict = {
            'query': sql_query,
            'start_time': timezone.now(),
            'traceback': tb
        }
        try:
            return self._execute_sql(*args, **kwargs)
        finally:
            query_dict['end_time'] = timezone.now()
            request = DataCollector().request
            if request:
                query_dict['request'] = request
            if self.query.model.__module__ != 'silk.models':
                DataCollector().register_query(query_dict)
            else:
                DataCollector().register_silk_query(query_dict)
    return self._execute_sql(*args, **kwargs)