Python django.db.models.QuerySet() Examples

The following are 30 code examples for showing how to use django.db.models.QuerySet(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: django-actions-logger   Author: shtalinberg   File: models.py    License: MIT License 6 votes vote down vote up
def get_for_objects(self, queryset):
        """
        Get log entries for the objects in the specified queryset.
        :param queryset: The queryset to get the log entries for.
        :type queryset: QuerySet
        :return: The LogAction objects for the objects in the given queryset.
        :rtype: QuerySet
        """
        if not isinstance(queryset, QuerySet) or queryset.count() == 0:
            return self.none()

        content_type = ContentType.objects.get_for_model(queryset.model)
        primary_keys = queryset.values_list(queryset.model._meta.pk.name, flat=True)

        if isinstance(primary_keys[0], integer_types):
            return self.filter(content_type=content_type).filter(Q(object_id__in=primary_keys)).distinct()
        else:
            return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct() 
Example 2
Project: django-cachalot   Author: noripyt   File: utils.py    License: 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 3
Project: karrot-backend   Author: yunity   File: tasks.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def daily_activity_notifications():

    with timer() as t:
        for group in Group.objects.all():
            with timezone.override(group.timezone):
                if timezone.localtime().hour != 20:  # only at 8pm local time
                    continue

                for data in fetch_activity_notification_data_for_group(group):
                    prepare_activity_notification_email(**data).send()
                    stats.activity_notification_email(
                        group=data['group'], **{k: v.count()
                                                for k, v in data.items() if isinstance(v, QuerySet)}
                    )

    stats_utils.periodic_task('activities__daily_activity_notifications', seconds=t.elapsed_seconds) 
Example 4
Project: djangochannelsrestframework   Author: hishnash   File: generics.py    License: MIT License 6 votes vote down vote up
def get_queryset(self, **kwargs) -> QuerySet:
        """
        Get the list of items for this view.
        This must be an iterable, and may be a queryset.
        Defaults to using `self.queryset`.

        This method should always be used rather than accessing `self.queryset`
        directly, as `self.queryset` gets evaluated only once, and those results
        are cached for all subsequent requests.

        You may want to override this if you need to provide different
        querysets depending on the incoming request.

        (Eg. return a list of items that is specific to the user)
        """
        assert self.queryset is not None, (
            "'%s' should either include a `queryset` attribute, "
            "or override the `get_queryset()` method." % self.__class__.__name__
        )

        queryset = self.queryset
        if isinstance(queryset, QuerySet):
            # Ensure queryset is re-evaluated on each request.
            queryset = queryset.all()
        return queryset 
Example 5
Project: lego   Author: webkom   File: backends.py    License: MIT License 6 votes vote down vote up
def has_perm(self, user_obj, perm, obj=None):
        if not user_obj.is_anonymous and not user_obj.is_active:
            return False

        if obj is None:
            # Take a shortcut and check KeywordPermissions only if no object are defined.
            return KeywordPermissions.has_perm(user_obj, perm)

        if isinstance(obj, models.Model):
            permission_handler = get_permission_handler(obj)
            return permission_handler.has_perm(user_obj, perm, obj=obj)
        elif isinstance(obj, models.QuerySet):
            permission_handler = get_permission_handler(obj.model)
            return permission_handler.has_perm(user_obj, perm, queryset=obj)
        elif issubclass(obj, models.Model):
            permission_handler = get_permission_handler(obj)
            return permission_handler.has_perm(
                user_obj, perm, queryset=obj.objects.none()
            )

        return False 
Example 6
Project: dynamic-rest   Author: AltSchool   File: prefetch.py    License: MIT License 6 votes vote down vote up
def _get_django_queryset(self):
        """Return Django QuerySet with prefetches properly configured."""

        prefetches = []
        for field, fprefetch in self.prefetches.items():
            has_query = hasattr(fprefetch, 'query')
            qs = fprefetch.query.queryset if has_query else None
            prefetches.append(
                Prefetch(field, queryset=qs)
            )

        queryset = self.queryset
        if prefetches:
            queryset = queryset.prefetch_related(*prefetches)

        return queryset 
Example 7
Project: dynamic-rest   Author: AltSchool   File: prefetch.py    License: MIT License 6 votes vote down vote up
def __getitem__(self, k):
        """Support list index and slicing, similar to Django QuerySet."""

        if self._data is not None:
            # Query has already been executed. Extract from local cache.
            return self._data[k]

        # Query hasn't yet been executed. Update queryset.
        if isinstance(k, slice):
            if k.start is not None:
                start = int(k.start)
            else:
                start = None
            if k.stop is not None:
                stop = int(k.stop)
            else:
                stop = None
            if k.step:
                raise TypeError("Stepping not supported")

            self.queryset.query.set_limits(start, stop)
            return self.execute()
        else:
            self.queryset.query.set_limits(k, k+1)
            return self.execute() 
Example 8
Project: django-carrot   Author: chris104957   File: api.py    License: Apache License 2.0 6 votes vote down vote up
def get_queryset(self) -> QuerySet:
        """
        Returns a queryset of `carrot.models.MessageLog` objects. If a `search_term` is provided in the request query
        params, then the result is filtered based on this. If using postgres, this is done using SearchVectors for
        improved performance
        """
        search_term = self.request.query_params.get('search', None)
        qs = self.queryset.all()
        if search_term:
            if settings.DATABASES.get('default', {}).get('ENGINE') == 'django.db.backends.postgresql_psycopg2':
                qs = qs.annotate(search=SearchVector('task', 'content', 'task_args')).filter(search=search_term)
            else:
                qs = (
                    qs.filter(task__icontains=search_term) |
                    qs.filter(content__icontains=search_term) |
                    qs.filter(task_args__icontains=search_term)
                ).distinct()

        return qs 
Example 9
Project: zing   Author: evernote   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _earliest_or_latest(self, field_name=None, direction="-"):
        """
        Overrides QuerySet._earliest_or_latest to add pk for secondary ordering
        """
        order_by = field_name or getattr(self.model._meta, "get_latest_by")
        assert bool(order_by), (
            "earliest() and latest() require either a "
            "field_name parameter or 'get_latest_by' in the model"
        )
        assert (
            self.query.can_filter()
        ), "Cannot change a query once a slice has been taken."
        obj = self._clone()
        obj.query.set_limits(high=1)
        obj.query.clear_ordering(force_empty=True)
        # add pk as secondary ordering for Submissions
        obj.query.add_ordering(
            "%s%s" % (direction, order_by), "%s%s" % (direction, "pk")
        )
        return obj.get() 
Example 10
Project: lexpredict-contraxsuite   Author: LexPredict   File: models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def drop_clusters(self, exclude_task_ids: Set = None, exclude_project_clustering_id: int = None):
        project = self
        # Stop running tusks
        from apps.task.tasks import purge_task
        from apps.project.tasks import ClusterProjectDocuments
        task_qr = project.project_tasks \
            .filter(name=ClusterProjectDocuments.name, status__in=UNREADY_STATES)  # type: QuerySet
        if exclude_task_ids:
            task_qr = task_qr.exclude(pk__in=exclude_task_ids)

        for task in task_qr:
            purge_task(task.pk, wait=True, timeout=1.5)
        # delete DocumentClusters
        for pcl in project.projectclustering_set.all():
            pcl.document_clusters.all().delete()
        # delete ProjectClustering
        project.projectclustering_set.exclude(id=exclude_project_clustering_id).delete()
        # delete ClusterProjectDocuments Tasks
        to_delete_qr = project.project_tasks.filter(name=ClusterProjectDocuments.name,
                                                    status__in=[SUCCESS, PENDING])  # type: QuerySet
        if exclude_task_ids:
            to_delete_qr = to_delete_qr.exclude(pk__in=exclude_task_ids)
        to_delete_qr.delete() 
Example 11
Project: lexpredict-contraxsuite   Author: LexPredict   File: features.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self,
                 queryset: Optional[Union[QuerySet, List[Document]]] = None,
                 project_id: Optional[int] = None,
                 project_name_filter: Optional[str] = None,
                 unit_type: str = 'sentence',
                 feature_source: str = 'term',
                 drop_empty_rows=True,
                 drop_empty_columns=True,
                 external_feature_names=None,
                 log_message: Callable[[str, str], None] = None):
        super().__init__(queryset, project_id, project_name_filter,
                         unit_type, feature_source,
                         drop_empty_rows, drop_empty_columns,
                         external_feature_names, log_message)
        self.transformer = None  # type: Optional[BaseTransformer]
        self.project_ids = []  # type: List[str] 
Example 12
Project: django-river   Author: javrasya   File: test__state_field.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_shouldInjectTheField(self):  # pylint: disable=no-self-use
        assert_that(BasicTestModel, has_property('river', is_(instance_of(RiverObject))))
        assert_that(BasicTestModel.river, has_property('my_field', is_(instance_of(ClassWorkflowObject))))

        content_type = ContentType.objects.get_for_model(BasicTestModel)

        state1 = StateObjectFactory.create(label="state1")
        state2 = StateObjectFactory.create(label="state2")

        workflow = WorkflowFactory(content_type=content_type, field_name="my_field", initial_state=state1)

        transition_meta = TransitionMetaFactory.create(
            workflow=workflow,
            source_state=state1,
            destination_state=state2,
        )

        TransitionApprovalMetaFactory.create(
            workflow=workflow,
            transition_meta=transition_meta,
            priority=0
        )
        test_model = BasicTestModel.objects.create()
        assert_that(test_model, has_property('river', is_(instance_of(RiverObject))))
        assert_that(test_model.river, has_property('my_field', is_(instance_of(InstanceWorkflowObject))))
        assert_that(BasicTestModel.river.my_field, has_property('initial_state', is_(instance_of(State))))
        assert_that(BasicTestModel.river.my_field, has_property('final_states', is_(instance_of(QuerySet))))

        assert_that(test_model.river.my_field, has_property('approve', has_property("__call__")))
        assert_that(test_model.river.my_field, has_property('on_initial_state', is_(instance_of(bool))))
        assert_that(test_model.river.my_field, has_property('on_final_state', is_(instance_of(bool)))) 
Example 13
Project: raveberry   Author: raveberry   File: song_queue.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def confirmed(self) -> QuerySet[QueuedSong]:
        """Returns a QuerySet containing all confirmed songs.
        Confirmed songs are not in the process of being made available."""
        return self.exclude(internal_url="") 
Example 14
Project: resolwe   Author: genialis   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def files(self) -> models.QuerySet:
        """Get referenced path objects in default storage location."""
        return self.default_storage_location.files 
Example 15
Project: resolwe   Author: genialis   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def get_queryset(self) -> models.QuerySet:
        """Override default queryset."""
        return super().get_queryset().filter(status="OK") 
Example 16
Project: resolwe   Author: genialis   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def unreferenced_locations(self) -> models.QuerySet:
        """Get a queryset containing all unreferenced locations.

        The location must also be unlocked (has no accesslogs with finished
        date set to null) to be included in the list.
        """
        return (
            StorageLocation.all_objects.filter(file_storage__data__isnull=True)
            .annotate(
                logs_num=models.Count(
                    "access_logs", filter=models.Q(access_logs__finished__isnull=True)
                )
            )
            .filter(logs_num=0)
        ) 
Example 17
Project: PrivacyScore   Author: PrivacyScore   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def ordered_columns(self) -> QuerySet:
        """Get the ordered column values of this site."""
        return self.sorted_columns 
Example 18
Project: django-actions-logger   Author: shtalinberg   File: models.py    License: MIT License 5 votes vote down vote up
def get_for_model(self, model):
        """
        Get log entries for all objects of a specified type.
        :param model: The model to get log entries for.
        :type model: class
        :return: QuerySet of log entries for the given model.
        :rtype: QuerySet
        """
        # Return empty queryset if the given object is not valid.
        if not issubclass(model, models.Model):
            return self.none()

        ct = ContentType.objects.get_for_model(model)

        return self.filter(content_type=ct) 
Example 19
Project: django-sitemessage   Author: idlesign   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_without_dispatches(cls) -> Union[List['Message'], QuerySet]:
        """Returns messages with no dispatches created."""
        return cls.objects.filter(dispatches_ready=False).all() 
Example 20
Project: django-sitemessage   Author: idlesign   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_unread(cls) -> Union[List['Dispatch'], QuerySet]:
        """Returns unread dispatches."""
        return cls.objects.filter(read_status=cls.READ_STATUS_UNDREAD).prefetch_related('message').all() 
Example 21
Project: django-sitemessage   Author: idlesign   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_for_user(cls, user: AbstractBaseUser) -> Union[List['Subscription'], QuerySet]:
        """Returns subscriptions for a given user.

        :param user:

        """
        if user.id is None:
            return []

        return cls.objects.filter(recipient=user) 
Example 22
Project: django-sitemessage   Author: idlesign   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_for_message_cls(cls, message_cls: str) -> Union[List['Subscription'], QuerySet]:
        """Returns subscriptions for a given message class alias.

        :param message_cls:

        """
        return cls.objects.select_related('recipient').filter(message_cls=message_cls) 
Example 23
Project: django-more   Author: ashleywaite   File: orderbyfield.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_next_expression(self, model_instance):
        """ Generate an expression that will evaluate to the next valid ordering value """
        # This will be the next number larger than existing records in the ordering set
        # If no records in the ordering set, start from 0
        # Evade any custom model managers
        qs = models.QuerySet(self.model).filter(**self.get_filter_kwargs_for_object(model_instance))
        qs = qs.annotate(_next=Max(self.attname) + 1).values('_next').order_by()
        # Hackishly clip group_by clause to guarantee single result
        qs.query.group_by = []
        return BypassExpression(Coalesce(Subquery(qs), 0, output_field=models.IntegerField())) 
Example 24
Project: django-polaris   Author: stellar   File: integrations.py    License: Apache License 2.0 5 votes vote down vote up
def poll_pending_deposits(self, pending_deposits: QuerySet) -> List[Transaction]:
        """
        Anchors should implement their banking rails here, as described
        in the :class:`.DepositIntegration` docstrings.

        This implementation interfaces with a fake banking rails client
        for demonstration purposes.
        """
        # interface with mock banking rails
        ready_deposits = []
        mock_bank_account_id = "XXXXXXXXXXXXX"
        client = rails.BankAPIClient(mock_bank_account_id)
        for deposit in pending_deposits:
            bank_deposit = client.get_deposit(memo=deposit.external_extra)
            if bank_deposit and bank_deposit.status == "complete":
                if not deposit.amount_in:
                    deposit.amount_in = Decimal(103)
                    deposit.amount_fee = calculate_fee(
                        {
                            "amount": 103,
                            "operation": settings.OPERATION_DEPOSIT,
                            "asset_code": deposit.asset.code,
                        }
                    )
                    deposit.save()
                ready_deposits.append(deposit)

        return ready_deposits 
Example 25
Project: django-trackstats   Author: pennersr   File: models.py    License: MIT License 5 votes vote down vote up
def narrow(self, **kwargs):
        qs = self
        object = kwargs.pop('object', None)
        objects = kwargs.pop('objects', None)
        object_type = kwargs.pop('object_type', None)
        assert object is None or objects is None
        if object is not None:
            objects = [object]
        if object_type:
            qs = qs.filter(object_type=object_type)
        if type(objects) in (list, tuple, set):
            if not objects:
                qs = self.none()
            else:
                # Assumption: all objects are of same type
                ct = ContentType.objects.get_for_model(objects[0])
                qs = qs.filter(
                    object_type=ct,
                    object_id__in=[s.pk for s in objects])
        elif isinstance(objects, models.QuerySet):
            ct = ContentType.objects.get_for_model(objects.model)
            qs = qs.filter(
                object_type=ct,
                object_id__in=objects.values_list(
                    'id', flat=True))
        elif objects is None:
            pass
        elif isinstance(objects, models.query.EmptyQuerySet):
            qs = self.none()
        else:
            raise NotImplementedError
        return super(ByObjectQuerySetMixin, qs).narrow(**kwargs) 
Example 26
Project: django-hordak   Author: adamcharnock   File: core.py    License: MIT License 5 votes vote down vote up
def sum_to_balance(self):
        """Sum the Legs of the QuerySet to get a `Balance`_ object
        """
        result = self.values("amount_currency").annotate(total=models.Sum("amount"))
        return Balance([Money(r["total"], r["amount_currency"]) for r in result]) 
Example 27
Project: djangochannelsrestframework   Author: hishnash   File: generics.py    License: MIT License 5 votes vote down vote up
def filter_queryset(self, queryset: QuerySet, **kwargs):
        """
        Given a queryset, filter it with whichever filter backend is in use.

        You are unlikely to want to override this method, although you may need
        to call it either from a list view, or from a custom `get_object`
        method if you want to apply the configured filtering backend to the
        default queryset.
        """
        # TODO filter_backends

        return queryset 
Example 28
Project: zulip   Author: zulip   File: client_activity.py    License: Apache License 2.0 5 votes vote down vote up
def compute_activity(self, user_activity_objects: QuerySet) -> None:
        # Report data from the past week.
        #
        # This is a rough report of client activity because we inconsistently
        # register activity from various clients; think of it as telling you
        # approximately how many people from a group have used a particular
        # client recently. For example, this might be useful to get a sense of
        # how popular different versions of a desktop client are.
        #
        # Importantly, this does NOT tell you anything about the relative
        # volumes of requests from clients.
        threshold = timezone_now() - datetime.timedelta(days=7)
        client_counts = user_activity_objects.filter(
            last_visit__gt=threshold).values("client__name").annotate(
            count=Count('client__name'))

        total = 0
        counts = []
        for client_type in client_counts:
            count = client_type["count"]
            client = client_type["client__name"]
            total += count
            counts.append((count, client))

        counts.sort()

        for count in counts:
            print(f"{count[1]:>25} {count[0]:15}")
        print("Total:", total) 
Example 29
Project: zulip   Author: zulip   File: render_messages.py    License: Apache License 2.0 5 votes vote down vote up
def queryset_iterator(queryset: QuerySet, chunksize: int=5000) -> Iterator[Any]:
    queryset = queryset.order_by('id')
    while queryset.exists():
        for row in queryset[:chunksize]:
            msg_id = row.id
            yield row
        queryset = queryset.filter(id__gt=msg_id) 
Example 30
Project: mangaki   Author: mangaki   File: mal.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def lookup_works(work_list: QuerySet,
                 ext_poster: str,
                 titles: List[str],
                 mal_id: int) -> List[Work]:
    """
    Look into the database all the works
    matching one of the `titles`, the external poster or
    an already referenced work.

    Raise ValueError when no `titles` (empty list) are given.

    :param work_list: A (filtered) QuerySet from Django starting from the Work model
    :type work_list: A queryset, e.g. `Work.objects.filter(category__slug='anime')`
    :param ext_poster: A string path to the external poster (a URL link)
    :type ext_poster: string
    :param titles: A list of potential titles that the work can hold, e.g. synonyms and unofficial titles.
    :type titles: list of strings
    :param mal_id: A MAL identifier
    :type mal_id: integer
    :return: a list of matching works (can be empty)
    :rtype: list of Work objects
    """
    if len(titles) == 0:
        raise ValueError('Empty list of `titles` !')

    works_ids_matched = set(
        work_list.filter(reference__source='MAL', reference__identifier=mal_id)
        .values_list('id', flat=True)
    )

    # Referenced works are source of truth (for now).
    return list(Work.objects.in_bulk(works_ids_matched).values()) if works_ids_matched else []