當前位置: 首頁>>代碼示例>>Python>>正文


Python models.Manager類代碼示例

本文整理匯總了Python中django.db.models.Manager的典型用法代碼示例。如果您正苦於以下問題:Python Manager類的具體用法?Python Manager怎麽用?Python Manager使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Manager類的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: manager_class

def manager_class(model, queryset_class=None, class_name=None,
                  use_for_related_fields=False):
    """
    Return the manager class for model.

    If an optional queryset is given, returns a new class using the
    Manager.from_queryset() API.
    """

    for cls in model.mro():
        if not issubclass(model, Model):
            continue
        try:
            mgm = cls.objects
            break
        except AttributeError:
            pass
    else:
        mgm = Manager()

    if not isinstance(mgm, BaseManager):
        raise TypeError('unexpected manager class: %s' %
                        mgm.__class__.__name__)

    if queryset_class is not None:
        mgm = mgm.from_queryset(queryset_class, class_name=class_name)

    if use_for_related_fields:
        mgm.use_for_related_fields = True

    return mgm
開發者ID:fabiommendes,項目名稱:codeschool,代碼行數:31,代碼來源:utils.py

示例2: base_manager

    def base_manager(self):
        base_manager_name = self.base_manager_name
        if not base_manager_name:
            # Get the first parent's base_manager_name if there's one.
            for parent in self.model.mro()[1:]:
                if hasattr(parent, '_meta'):
                    if parent._base_manager.name != '_base_manager':
                        base_manager_name = parent._base_manager.name
                    break

        if base_manager_name:
            try:
                return self.managers_map[base_manager_name]
            except KeyError:
                raise ValueError(
                    "%s has no manager named %r" % (
                        self.object_name,
                        base_manager_name,
                    )
                )

        manager = Manager()
        manager.name = '_base_manager'
        manager.model = self.model
        manager.auto_created = True
        return manager
開發者ID:agmond,項目名稱:django,代碼行數:26,代碼來源:options.py

示例3: test_consider_real_django_fields_only

 def test_consider_real_django_fields_only(self):
     id_ = ModelWithImpostorField._meta.get_field('id')
     with patch.object(mommy.Mommy, 'get_fields') as mock:
         f = Manager()
         f.name = 'foo'
         mock.return_value = [id_, f]
         try:
             mommy.make(ModelWithImpostorField)
         except TypeError:
             self.fail('TypeError raised')
開發者ID:helber,項目名稱:model_mommy,代碼行數:10,代碼來源:test_mommy.py

示例4: test_consider_real_django_fields_only

 def test_consider_real_django_fields_only(self):
     id_ = models.ModelWithImpostorField._meta.get_field("id")
     with patch.object(mommy.Mommy, "get_fields") as mock:
         f = Manager()
         f.name = "foo"
         mock.return_value = [id_, f]
         try:
             mommy.make(models.ModelWithImpostorField)
         except TypeError:
             self.fail("TypeError raised")
開發者ID:renatooliveira,項目名稱:model_mommy,代碼行數:10,代碼來源:test_mommy.py

示例5: base_manager

    def base_manager(self):
        base_manager_name = self.base_manager_name
        if not base_manager_name:
            # Get the first parent's base_manager_name if there's one.
            for parent in self.model.mro()[1:]:
                if hasattr(parent, '_meta'):
                    if parent._base_manager.name != '_base_manager':
                        base_manager_name = parent._base_manager.name
                    break

        if base_manager_name:
            try:
                return self.managers_map[base_manager_name]
            except KeyError:
                raise ValueError(
                    "%s has no manager named %r" % (
                        self.object_name,
                        base_manager_name,
                    )
                )

        # Deprecation shim for `use_for_related_fields`.
        for i, base_manager_class in enumerate(self.default_manager.__class__.mro()):
            if getattr(base_manager_class, 'use_for_related_fields', False):
                if not getattr(base_manager_class, 'silence_use_for_related_fields_deprecation', False):
                    warnings.warn(
                        "use_for_related_fields is deprecated, instead "
                        "set Meta.base_manager_name on '{}'.".format(self.model._meta.label),
                        RemovedInDjango20Warning, 2
                    )

                if i == 0:
                    manager = self.default_manager
                else:
                    manager = base_manager_class()
                    manager.name = '_base_manager'
                    manager.model = self.model

                return manager

        manager = Manager()
        manager.name = '_base_manager'
        manager.model = self.model
        manager.auto_created = True
        return manager
開發者ID:AMontagu,項目名稱:django,代碼行數:45,代碼來源:options.py

示例6: RedirectQuerySet

# -*- coding: utf-8 -*-

"""Manager and queryset for the redirects app."""

from django.db.models import Manager
from django.db.models.query import QuerySet


class RedirectQuerySet(QuerySet):

    def get_redirect_path(self, path, language=None, version_slug=None):
        for redirect in self.select_related('project'):
            new_path = redirect.get_redirect_path(
                path=path,
                language=language,
                version_slug=version_slug,
            )
            if new_path:
                return new_path
        return None


RedirectManager = Manager.from_queryset(RedirectQuerySet)
開發者ID:chrisjsewell,項目名稱:readthedocs.org,代碼行數:23,代碼來源:managers.py

示例7:

# -*- coding: utf-8 -*-
from __future__ import absolute_import

from django.db.models import Manager

# Need to substitute model_utils in Django<1.7
try:
    Manager.from_queryset
except AttributeError:
    from model_utils.managers import PassThroughManager as Manager
    Manager.from_queryset = Manager.for_queryset_class

from .queryset import CursorQueryset


CursorManager = Manager.from_queryset(CursorQueryset)
開發者ID:kevinastone,項目名稱:django-cursor-pagination,代碼行數:16,代碼來源:managers.py

示例8: FuzzyCountQuerySet

from django.db import connections
from django.db.models import QuerySet, Manager
from django.db.models.sql.datastructures import EmptyResultSet


class FuzzyCountQuerySet(QuerySet):

    def fuzzy_count(self):
        cursor = connections[self.db].cursor()

        try:
            cursor.execute('SELECT count_estimate(%s);', (cursor.mogrify(*self.query.sql_with_params()).decode(), ))
        except EmptyResultSet:
            return 0

        return int(cursor.fetchone()[0])

FuzzyCountManager = Manager.from_queryset(FuzzyCountQuerySet)
開發者ID:Stevenholloway,項目名稱:SHARE,代碼行數:18,代碼來源:fuzzycount.py

示例9: import

from mozillians.phonebook.validators import (validate_email, validate_twitter,
                                             validate_website, validate_username_not_url,
                                             validate_phone_number, validate_linkedin,
                                             validate_discord)
from mozillians.users import get_languages_for_locale
from mozillians.users.managers import (EMPLOYEES,
                                       MOZILLIANS, PRIVACY_CHOICES, PRIVACY_CHOICES_WITH_PRIVATE,
                                       PRIVATE, PUBLIC, PUBLIC_INDEXABLE_FIELDS,
                                       UserProfileQuerySet)
from mozillians.users.tasks import send_userprofile_to_cis


COUNTRIES = product_details.get_regions('en-US')
AVATAR_SIZE = (300, 300)
logger = logging.getLogger(__name__)
ProfileManager = Manager.from_queryset(UserProfileQuerySet)


def _calculate_photo_filename(instance, filename):
    """Generate a unique filename for uploaded photo."""
    return os.path.join(settings.USER_AVATAR_DIR, str(uuid.uuid4()) + '.jpg')


class PrivacyField(models.PositiveSmallIntegerField):

    def __init__(self, *args, **kwargs):
        myargs = {'default': MOZILLIANS,
                  'choices': PRIVACY_CHOICES}
        myargs.update(kwargs)
        super(PrivacyField, self).__init__(*args, **myargs)
開發者ID:yahkrivetko,項目名稱:mozillians,代碼行數:30,代碼來源:models.py

示例10:

from django.db.models import Manager

from .querysets import OrderableQueryset


OrderableManager = Manager.from_queryset(OrderableQueryset)
開發者ID:incuna,項目名稱:django-orderable,代碼行數:6,代碼來源:managers.py

示例11: SUM

# Closest equivalent to SUM in Django
from django.db.models import Manager

result = Manager.raw(u"""select SUM(royalty_price*conversion_to_usd)from sales_raw where date='2012-06-01'""")
開發者ID:fiolbs,項目名稱:code_extraction,代碼行數:4,代碼來源:python_23599.py

示例12: list

            self._result_cache = list(self.iterator())
        has_prefetch_relateds = len(self._prefetch_related_lookups) > 0
        has_prefetch_models = len(self._our_prefetches) > 0
        needs_prefetches = has_prefetch_relateds or has_prefetch_models
        if needs_prefetches and not self._prefetch_done:
            self._prefetch_related_objects()


    def iterator(self):
        iterator = super(InheritingQuerySet, self).iterator()
        relations_for_attrgetter = tuple(x.replace(LOOKUP_SEP, '.') for x in lookups_to_text(self._our_joins))
        print(relations_for_attrgetter)
        attrgetters = tuple(attrgetter(x) for x in relations_for_attrgetter)
        for obj in iterator:
            yield dig_for_obj(obj=obj, attrgetters=attrgetters)
    #
    def _prefetch_related_objects(self):
        things = defaultdict(list)
        for index, thing in enumerate(self._result_cache, start=0):
            things[thing.__class__].append(thing)

        for klass, instances in things.items():
            prefetches = self._prefetch_related_lookups[:]
            if klass in self._our_prefetches:
                prefetches.extend(self._our_prefetches[klass])
            prefetch_related_objects(instances, prefetches)
        return None


InheritingManager = Manager.from_queryset(InheritingQuerySet)
開發者ID:kezabelle,項目名稱:django-inheritrix,代碼行數:30,代碼來源:inheritrix.py


注:本文中的django.db.models.Manager類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。