当前位置: 首页>>代码示例>>Python>>正文


Python query.QuerySet方法代码示例

本文整理汇总了Python中django.db.models.query.QuerySet方法的典型用法代码示例。如果您正苦于以下问题:Python query.QuerySet方法的具体用法?Python query.QuerySet怎么用?Python query.QuerySet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.models.query的用法示例。


在下文中一共展示了query.QuerySet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load_queryset

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def load_queryset(self, query_data, request, *args, **kwargs):
        """
        Fetches the queryset and runs any necessary filtering, both
        built-in rest_framework filters and custom filters passed into
        the querylist
        """
        queryset = query_data.get('queryset', [])

        if isinstance(queryset, QuerySet):
            # Ensure queryset is re-evaluated on each request.
            queryset = queryset.all()

        # run rest_framework filters
        queryset = self.filter_queryset(queryset)

        # run custom filters
        filter_fn = query_data.get('filter_fn', None)
        if filter_fn is not None:
            queryset = filter_fn(queryset, request, *args, **kwargs)

        page = self.paginate_queryset(queryset)
        self.is_paginated = page is not None

        return page if page is not None else queryset 
开发者ID:MattBroach,项目名称:DjangoRestMultipleModels,代码行数:26,代码来源:mixins.py

示例2: test_multi_perms_no_groups

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def test_multi_perms_no_groups(self):
        group_names = ["group1", "group2", "group3"]
        groups = [Group.objects.create(name=name) for name in group_names]
        for group in groups:
            assign_perm("auth.change_group", self.contributor, group)
        assign_perm("auth.delete_group", self.contributor, groups[1])

        objects = get_objects_for_user(
            self.contributor,
            ["auth.change_group", "auth.delete_group"],
            use_groups=False,
        )
        self.assertEqual(len(objects), 1)
        self.assertTrue(isinstance(objects, QuerySet))
        self.assertEqual(
            set(objects.values_list("name", flat=True)), set([groups[1].name])
        ) 
开发者ID:genialis,项目名称:resolwe,代码行数:19,代码来源:test_shortcuts.py

示例3: _get_queryset

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def _get_queryset(klass):
    """
    Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
    get_object_or_404 and get_list_or_404 more DRY.

    Raises a ValueError if klass is not a Model, Manager, or QuerySet.
    """
    if isinstance(klass, QuerySet):
        return klass
    elif isinstance(klass, Manager):
        manager = klass
    elif isinstance(klass, ModelBase):
        manager = klass._default_manager
    else:
        if isinstance(klass, type):
            klass__name = klass.__name__
        else:
            klass__name = klass.__class__.__name__
        raise ValueError("Object is of type '%s', but must be a Django Model, "
                         "Manager, or QuerySet" % klass__name)
    return manager.all() 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:23,代码来源:shortcuts.py

示例4: get_object_or_404

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def get_object_or_404(klass, *args, **kwargs):
    """
    Uses get() to return an object, or raises a Http404 exception if the object
    does not exist.

    klass may be a Model, Manager, or QuerySet object. All other passed
    arguments and keyword arguments are used in the get() query.

    Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
    object is found.
    """
    queryset = _get_queryset(klass)
    try:
        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:shortcuts.py

示例5: test_get_db_obj_query_with_columns

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def test_get_db_obj_query_with_columns(self):
        """Test that a query is returned with limited columns."""
        table_name = OCP_REPORT_TABLE_MAP["line_item"]
        columns = list(REPORT_COLUMN_MAP[table_name].values())

        selected_columns = [random.choice(columns) for _ in range(2)]
        missing_columns = set(columns).difference(selected_columns)

        query = self.accessor._get_db_obj_query(table_name, columns=selected_columns)
        self.assertIsInstance(query, QuerySet)
        with schema_context(self.schema):
            result = query.first()

            for column in selected_columns:
                self.assertTrue(column in result)

            for column in missing_columns:
                self.assertFalse(column in result) 
开发者ID:project-koku,项目名称:koku,代码行数:20,代码来源:test_ocp_report_db_accessor.py

示例6: test_get_db_obj_query_with_columns

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def test_get_db_obj_query_with_columns(self):
        """Test that a query is returned with limited columns."""
        table_name = random.choice(self.foreign_key_tables)
        columns = list(REPORT_COLUMN_MAP[table_name].values())

        selected_columns = [random.choice(columns) for _ in range(2)]
        missing_columns = set(columns).difference(selected_columns)

        query = self.accessor._get_db_obj_query(table_name, columns=selected_columns)
        with schema_context(self.schema):
            self.assertIsInstance(query, QuerySet)
            result = query.first()
            for column in selected_columns:
                self.assertTrue(column in result)

            for column in missing_columns:
                self.assertFalse(column in result) 
开发者ID:project-koku,项目名称:koku,代码行数:19,代码来源:test_aws_report_db_accessor.py

示例7: content

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def content(self, value):
        workbook = None
        if not bool(value) or not len(value):  # Short-circuit to protect against empty querysets/empty lists/None, etc
            self._container = []
            return
        elif isinstance(value, list):
            workbook = self._serialize_list(value)
        elif isinstance(value, QuerySet):
            workbook = self._serialize_queryset(value)
        if django.VERSION < (1, 9):
            if isinstance(value, ValuesQuerySet):
                workbook = self._serialize_values_queryset(value)
        if workbook is None:
            raise ValueError('ExcelResponse accepts the following data types: list, dict, QuerySet, ValuesQuerySet')

        if self.force_csv:
            self['Content-Type'] = 'text/csv; charset=utf8'
            self['Content-Disposition'] = 'attachment;filename="{}.csv"'.format(self.output_filename)
            workbook.seek(0)
            workbook = self.make_bytes(workbook.getvalue())
        else:
            self['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            self['Content-Disposition'] = 'attachment; filename="{}.xlsx"'.format(self.output_filename)
            workbook = save_virtual_workbook(workbook)
        self._container = [self.make_bytes(workbook)] 
开发者ID:tarkatronic,项目名称:django-excel-response,代码行数:27,代码来源:response.py

示例8: query_for_ids

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def query_for_ids(query: QuerySet, user_ids: List[int], field: str) -> QuerySet:
    '''
    This function optimizes searches of the form
    `user_profile_id in (1, 2, 3, 4)` by quickly
    building the where clauses.  Profiling shows significant
    speedups over the normal Django-based approach.

    Use this very carefully!  Also, the caller should
    guard against empty lists of user_ids.
    '''
    assert(user_ids)
    clause = f'{field} IN %s'
    query = query.extra(
        where=[clause], params=(tuple(user_ids),),
    )
    return query

# Doing 1000 remote cache requests to get_display_recipient is quite slow,
# so add a local cache as well as the remote cache cache.
#
# This local cache has a lifetime of just a single request; it is
# cleared inside `flush_per_request_caches` in our middleware.  It
# could be replaced with smarter bulk-fetching logic that deduplicates
# queries for the same recipient; this is just a convenient way to
# write that code. 
开发者ID:zulip,项目名称:zulip,代码行数:27,代码来源:models.py

示例9: get_users_by_delivery_email

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def get_users_by_delivery_email(emails: Set[str], realm: Realm) -> QuerySet:
    """This is similar to get_users_by_delivery_email, and
    it has the same security caveats.  It gets multiple
    users and returns a QuerySet, since most callers
    will only need two or three fields.

    If you are using this to get large UserProfile objects, you are
    probably making a mistake, but if you must,
    then use `select_related`.
    """

    '''
    Django doesn't support delivery_email__iexact__in, so
    we simply OR all the filters that we'd do for the
    one-email case.
    '''
    email_filter = Q()
    for email in emails:
        email_filter |= Q(delivery_email__iexact=email.strip())

    return UserProfile.objects.filter(realm=realm).filter(email_filter) 
开发者ID:zulip,项目名称:zulip,代码行数:23,代码来源:models.py

示例10: user_profile_to_user_row

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def user_profile_to_user_row(user_profile: UserProfile) -> Dict[str, Any]:
    # What we're trying to do is simulate the user_profile having been
    # fetched from a QuerySet using `.values(*realm_user_dict_fields)`
    # even though we fetched UserProfile objects.  This is messier
    # than it seems.
    #
    # What we'd like to do is just call model_to_dict(user,
    # fields=realm_user_dict_fields).  The problem with this is
    # that model_to_dict has a different convention than
    # `.values()` in its handling of foreign keys, naming them as
    # e.g. `bot_owner`, not `bot_owner_id`; we work around that
    # here.
    #
    # This could be potentially simplified in the future by
    # changing realm_user_dict_fields to name the bot owner with
    # the less readable `bot_owner` (instead of `bot_owner_id`).
    user_row = model_to_dict(user_profile,
                             fields=realm_user_dict_fields + ['bot_owner'])
    user_row['bot_owner_id'] = user_row['bot_owner']
    del user_row['bot_owner']
    return user_row 
开发者ID:zulip,项目名称:zulip,代码行数:23,代码来源:users.py

示例11: get_user_activity_records_for_realm

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def get_user_activity_records_for_realm(realm: str, is_bot: bool) -> QuerySet:
    fields = [
        'user_profile__full_name',
        'user_profile__delivery_email',
        'query',
        'client__name',
        'count',
        'last_visit',
    ]

    records = UserActivity.objects.filter(
        user_profile__realm__string_id=realm,
        user_profile__is_active=True,
        user_profile__is_bot=is_bot,
    )
    records = records.order_by("user_profile__delivery_email", "-last_visit")
    records = records.select_related('user_profile', 'client').only(*fields)
    return records 
开发者ID:zulip,项目名称:zulip,代码行数:20,代码来源:views.py

示例12: raw_user_activity_table

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def raw_user_activity_table(records: List[QuerySet]) -> str:
    cols = [
        'query',
        'client',
        'count',
        'last_visit',
    ]

    def row(record: QuerySet) -> List[Any]:
        return [
            record.query,
            record.client.name,
            record.count,
            format_date_for_activity_reports(record.last_visit),
        ]

    rows = list(map(row, records))
    title = 'Raw Data'
    return make_table(title, cols, rows) 
开发者ID:zulip,项目名称:zulip,代码行数:21,代码来源:views.py

示例13: get_queryset

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def get_queryset(self):
        if self.queryset is not None:
            queryset = self.queryset
            if isinstance(queryset, QuerySet):
                queryset = queryset.all()
        elif self.model is not None:
            queryset = self.model._default_manager.all()
        else:
            raise ImproperlyConfigured(
                "%(cls)s is missing a QuerySet. Define "
                "%(cls)s.model, %(cls)s.queryset, or override "
                "%(cls)s.get_queryset()." % {
                    'cls': self.__class__.__name__
                }
            )
        ordering = self.get_ordering()
        if ordering:
            if isinstance(ordering, six.string_types):
                ordering = (ordering,)
            queryset = queryset.order_by(*ordering)
        return queryset 
开发者ID:jlmadurga,项目名称:django-telegram-bot,代码行数:23,代码来源:list.py

示例14: bind

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def bind(self, field_name, parent):
        try:
            renderer = parent.context['request'].accepted_renderer
        except (AttributeError, KeyError):
            pass
        else:
            obj = parent.root.instance
            try:
                has_format = renderer.format in obj.query.annotations
            except AttributeError:
                if not isinstance(obj, QuerySet):
                    try:
                        obj = obj[0]
                    except (IndexError, TypeError):
                        pass
                has_format = hasattr(obj, renderer.format)
            if has_format:
                self.source = renderer.format
        super(GeometryField, self).bind(field_name, parent) 
开发者ID:bkg,项目名称:django-spillway,代码行数:21,代码来源:fields.py

示例15: update_features

# 需要导入模块: from django.db.models import query [as 别名]
# 或者: from django.db.models.query import QuerySet [as 别名]
def update_features(self, query_set):
        """
            Updates the features property ManyToMany with the features returned by self.create_query_set, whose
            QuerySet is based upon the current values of the LayerSelection instance
            :param query_set: The query_set from create_query_set or similar
        :return:
        """
        self.clear_features()
        if not query_set:
            # If none keep features clear and return
            return
        # Update the features based on the new query_set
        self.features.through.objects.bulk_create(
            map(
                lambda feature: self.features.through(
                    feature=feature,
                    layer_selection=self),
                query_set.all()
            )
        ) 
开发者ID:CalthorpeAnalytics,项目名称:urbanfootprint,代码行数:22,代码来源:layer_selection.py


注:本文中的django.db.models.query.QuerySet方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。