本文整理汇总了Python中django.db.models.manager.Manager方法的典型用法代码示例。如果您正苦于以下问题:Python manager.Manager方法的具体用法?Python manager.Manager怎么用?Python manager.Manager使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models.manager
的用法示例。
在下文中一共展示了manager.Manager方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_attr
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def _get_attr(model_data, time_func, foreign, many):
dic_list = {}
attr_list = model_data._meta.get_all_field_names()
for itm in attr_list:
attribute = getattr(model_data, itm)
if isinstance(attribute, models.Model):
if foreign:
dic_list[itm] = _get_attr(attribute, time_func, foreign, many)
elif isinstance(attribute, manager.Manager):
if many and not str(itm).endswith('_art'):
many_obj = attribute.all()
many_list = []
for mitm in many_obj:
many_item = _get_attr(mitm, time_func, foreign, many)
many_list.append(many_item)
dic_list[itm] = many_list
elif isinstance(attribute, datetime.datetime):
dic_list[itm] = time_func(getattr(model_data, itm))
else:
dic_list[itm] = getattr(model_data, itm)
if '_state' in dic_list:
dic_list.pop('_state')
return dic_list
示例2: _get_queryset
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [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()
示例3: get_object_or_404
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [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)
示例4: post
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def post(self, request, *args, **kwargs):
related_instance_or_manager = self.get_related_instance()
if isinstance(related_instance_or_manager, Manager):
related_model_class = related_instance_or_manager.model
serializer = self.get_serializer(
data=request.data, model_class=related_model_class, many=True
)
serializer.is_valid(raise_exception=True)
if frozenset(serializer.validated_data) <= frozenset(related_instance_or_manager.all()):
return Response(status=204)
related_instance_or_manager.add(*serializer.validated_data)
else:
raise MethodNotAllowed('POST')
result_serializer = self._instantiate_serializer(related_instance_or_manager)
return Response(result_serializer.data)
示例5: delete
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def delete(self, request, *args, **kwargs):
related_instance_or_manager = self.get_related_instance()
if isinstance(related_instance_or_manager, Manager):
related_model_class = related_instance_or_manager.model
serializer = self.get_serializer(
data=request.data, model_class=related_model_class, many=True
)
serializer.is_valid(raise_exception=True)
objects = related_instance_or_manager.all()
if frozenset(serializer.validated_data).isdisjoint(frozenset(objects)):
return Response(status=204)
try:
related_instance_or_manager.remove(*serializer.validated_data)
except AttributeError:
raise Conflict(
'This object cannot be removed from this relationship without being '
'added to another'
)
else:
raise MethodNotAllowed('DELETE')
result_serializer = self._instantiate_serializer(related_instance_or_manager)
return Response(result_serializer.data)
示例6: _get_queryset
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [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:
klass__name = klass.__name__ if isinstance(klass, type) \
else klass.__class__.__name__
raise ValueError("Object is of type '%s', but must be a Django Model, "
"Manager, or QuerySet" % klass__name)
return manager.all()
示例7: get_list_or_404
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def get_list_or_404(klass, *args, **kwargs):
"""
Uses filter() to return a list of objects, or raise a Http404 exception if
the list is empty.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the filter() query.
"""
queryset = _get_queryset(klass)
obj_list = list(queryset.filter(*args, **kwargs))
if not obj_list:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
return obj_list
示例8: patch
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def patch(self, request, *args, **kwargs):
parent_obj = self.get_object()
related_instance_or_manager = self.get_related_instance()
if isinstance(related_instance_or_manager, Manager):
related_model_class = related_instance_or_manager.model
serializer = self.get_serializer(
data=request.data, model_class=related_model_class, many=True
)
serializer.is_valid(raise_exception=True)
# for to one
if hasattr(related_instance_or_manager, "field"):
related_instance_or_manager = self.remove_relationships(
instance_manager=related_instance_or_manager, field="field")
# for to many
else:
related_instance_or_manager = self.remove_relationships(
instance_manager=related_instance_or_manager, field="target_field")
# have to set bulk to False since data isn't saved yet
class_name = related_instance_or_manager.__class__.__name__
if class_name != 'ManyRelatedManager':
related_instance_or_manager.add(*serializer.validated_data, bulk=False)
else:
related_instance_or_manager.add(*serializer.validated_data)
else:
related_model_class = related_instance_or_manager.__class__
serializer = self.get_serializer(data=request.data, model_class=related_model_class)
serializer.is_valid(raise_exception=True)
setattr(parent_obj, self.get_related_field_name(), serializer.validated_data)
parent_obj.save()
related_instance_or_manager = self.get_related_instance() # Refresh instance
result_serializer = self._instantiate_serializer(related_instance_or_manager)
return Response(result_serializer.data)
示例9: _instantiate_serializer
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def _instantiate_serializer(self, instance):
if isinstance(instance, Model) or instance is None:
return self.get_serializer(instance=instance)
else:
if isinstance(instance, (QuerySet, Manager)):
instance = instance.all()
return self.get_serializer(instance=instance, many=True)
示例10: maybe_queryset
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def maybe_queryset(value):
if isinstance(value, Manager):
value = value.get_queryset()
return value
示例11: to_representation
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def to_representation(self, data):
results = OrderedDict()
iterable = data.all() if isinstance(data, Manager) else data
for item in iterable:
search_index_name = self.__get_keyName(item)
results.setdefault(search_index_name, []).append(
self.child.to_representation(item)
)
return results
示例12: to_representation
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def to_representation(self, data):
results = OrderedDict()
iterable = data.all() if isinstance(data, Manager) else data
for item in iterable:
searchIndexName = self.__get_keyName(item)
results.setdefault(searchIndexName, []).append(self.child.to_representation(item))
return results
示例13: _prepare
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def _prepare(cls):
"""Create some methods once self._meta has been populated."""
opts = cls._meta
opts._prepare(cls)
if opts.order_with_respect_to:
cls.get_next_in_order = partialmethod(cls._get_next_or_previous_in_order, is_next=True)
cls.get_previous_in_order = partialmethod(cls._get_next_or_previous_in_order, is_next=False)
# Defer creating accessors on the foreign class until it has been
# created and registered. If remote_field is None, we're ordering
# with respect to a GenericForeignKey and don't know what the
# foreign class is - we'll add those accessors later in
# contribute_to_class().
if opts.order_with_respect_to.remote_field:
wrt = opts.order_with_respect_to
remote = wrt.remote_field.model
lazy_related_operation(make_foreign_order_accessors, cls, remote)
# Give the class a docstring -- its definition.
if cls.__doc__ is None:
cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join(f.name for f in opts.fields))
get_absolute_url_override = settings.ABSOLUTE_URL_OVERRIDES.get(opts.label_lower)
if get_absolute_url_override:
setattr(cls, 'get_absolute_url', get_absolute_url_override)
if not opts.managers:
if any(f.name == 'objects' for f in opts.fields):
raise ValueError(
"Model %s must specify a custom Manager, because it has a "
"field named 'objects'." % cls.__name__
)
manager = Manager()
manager.auto_created = True
cls.add_to_class('objects', manager)
# Set the name of _meta.indexes. This can't be done in
# Options.contribute_to_class() because fields haven't been added to
# the model at that point.
for index in cls._meta.indexes:
if not index.name:
index.set_name_with_model(cls)
class_prepared.send(sender=cls)
示例14: _prepare
# 需要导入模块: from django.db.models import manager [as 别名]
# 或者: from django.db.models.manager import Manager [as 别名]
def _prepare(cls):
"""
Creates some methods once self._meta has been populated.
"""
opts = cls._meta
opts._prepare(cls)
if opts.order_with_respect_to:
cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True)
cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False)
# Defer creating accessors on the foreign class until it has been
# created and registered. If remote_field is None, we're ordering
# with respect to a GenericForeignKey and don't know what the
# foreign class is - we'll add those accessors later in
# contribute_to_class().
if opts.order_with_respect_to.remote_field:
wrt = opts.order_with_respect_to
remote = wrt.remote_field.model
lazy_related_operation(make_foreign_order_accessors, cls, remote)
# Give the class a docstring -- its definition.
if cls.__doc__ is None:
cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join(f.name for f in opts.fields))
get_absolute_url_override = settings.ABSOLUTE_URL_OVERRIDES.get(opts.label_lower)
if get_absolute_url_override:
setattr(cls, 'get_absolute_url', get_absolute_url_override)
if not opts.managers or cls._requires_legacy_default_manager():
if any(f.name == 'objects' for f in opts.fields):
raise ValueError(
"Model %s must specify a custom Manager, because it has a "
"field named 'objects'." % cls.__name__
)
manager = Manager()
manager.auto_created = True
cls.add_to_class('objects', manager)
# Set the name of _meta.indexes. This can't be done in
# Options.contribute_to_class() because fields haven't been added to
# the model at that point.
for index in cls._meta.indexes:
if not index.name:
index.set_name_with_model(cls)
class_prepared.send(sender=cls)