Python django.db.models.manager.Manager() Examples
The following are 22
code examples of django.db.models.manager.Manager().
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 also want to check out all available functions/classes of the module
django.db.models.manager
, or try the search function
.
Example #1
Source File: Serializer.py From django-angularjs-blog with BSD 2-Clause "Simplified" License | 6 votes |
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
Example #2
Source File: shortcuts.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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)
Example #3
Source File: views.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #4
Source File: views.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #5
Source File: shortcuts.py From openhgsenti with Apache License 2.0 | 6 votes |
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)
Example #6
Source File: shortcuts.py From openhgsenti with Apache License 2.0 | 6 votes |
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()
Example #7
Source File: __init__.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
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()
Example #8
Source File: __init__.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
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)
Example #9
Source File: search.py From TheOrgBook with Apache License 2.0 | 5 votes |
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
Example #10
Source File: search_serializers.py From indy-ssivc-tutorial with Apache License 2.0 | 5 votes |
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
Example #11
Source File: search.py From aries-vcr with Apache License 2.0 | 5 votes |
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
Example #12
Source File: utils.py From graphene-django with MIT License | 5 votes |
def maybe_queryset(value): if isinstance(value, Manager): value = value.get_queryset() return value
Example #13
Source File: shortcuts.py From openhgsenti with Apache License 2.0 | 5 votes |
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
Example #14
Source File: __init__.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
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
Example #15
Source File: views.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 5 votes |
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)
Example #16
Source File: views.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 5 votes |
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)
Example #17
Source File: shortcuts.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
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
Example #18
Source File: shortcuts.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
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()
Example #19
Source File: base.py From python with Apache License 2.0 | 4 votes |
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)
Example #20
Source File: base.py From Hands-On-Application-Development-with-PyCharm with MIT License | 4 votes |
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)
Example #21
Source File: base.py From python2017 with MIT License | 4 votes |
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)
Example #22
Source File: base.py From bioforum with MIT License | 4 votes |
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)