本文整理汇总了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
示例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
示例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')
示例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")
示例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
示例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)
示例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)
示例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)
示例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)
示例10:
from django.db.models import Manager
from .querysets import OrderableQueryset
OrderableManager = Manager.from_queryset(OrderableQueryset)
示例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'""")
示例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)