Python django.db.models.Manager() Examples

The following are 30 code examples for showing how to use django.db.models.Manager(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_object_or_None(model_thing, **kwargs):
    """
    Shortcut to catch the exception thrown by Model.objects.get if nothing is found and
    returns None instead.

    Example:
        obj = get_object_or_None(MyModelClass, id=3)
    """
    if isinstance(model_thing, models.Manager):
        try:
            return model_thing.get(**kwargs)
        except model_thing.model.DoesNotExist:
            return None
    else:
        try:
            return model_thing.objects.get(**kwargs)
        except model_thing.DoesNotExist:
            return None 
Example 2
Project: GTDWeb   Author: lanbing510   File: models.py    License: GNU General Public License v2.0 6 votes vote down vote up
def deconstruct(self):
        kwargs = {
            'name': self.name,
            'fields': self.fields,
        }
        if self.options:
            kwargs['options'] = self.options
        if self.bases and self.bases != (models.Model,):
            kwargs['bases'] = self.bases
        if self.managers and self.managers != [('objects', models.Manager())]:
            kwargs['managers'] = self.managers
        return (
            self.__class__.__name__,
            [],
            kwargs
        ) 
Example 3
Project: bioforum   Author: reBiocoder   File: models.py    License: MIT License 6 votes vote down vote up
def deconstruct(self):
        kwargs = {
            'name': self.name,
            'fields': self.fields,
        }
        if self.options:
            kwargs['options'] = self.options
        if self.bases and self.bases != (models.Model,):
            kwargs['bases'] = self.bases
        if self.managers and self.managers != [('objects', models.Manager())]:
            kwargs['managers'] = self.managers
        return (
            self.__class__.__qualname__,
            [],
            kwargs
        ) 
Example 4
Project: django-rest-framework-json-api   Author: django-json-api   File: utils.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_relation_instance(resource_instance, source, serializer):
    try:
        relation_instance = operator.attrgetter(source)(resource_instance)
    except AttributeError:
        # if the field is not defined on the model then we check the serializer
        # and if no value is there we skip over the field completely
        serializer_method = getattr(serializer, source, None)
        if serializer_method and hasattr(serializer_method, '__call__'):
            relation_instance = serializer_method(resource_instance)
        else:
            return False, None

    if isinstance(relation_instance, Manager):
        relation_instance = relation_instance.all()

    return True, relation_instance 
Example 5
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: models.py    License: MIT License 6 votes vote down vote up
def deconstruct(self):
        kwargs = {
            'name': self.name,
            'fields': self.fields,
        }
        if self.options:
            kwargs['options'] = self.options
        if self.bases and self.bases != (models.Model,):
            kwargs['bases'] = self.bases
        if self.managers and self.managers != [('objects', models.Manager())]:
            kwargs['managers'] = self.managers
        return (
            self.__class__.__qualname__,
            [],
            kwargs
        ) 
Example 6
Project: python   Author: Yeah-Kun   File: models.py    License: Apache License 2.0 6 votes vote down vote up
def deconstruct(self):
        kwargs = {
            'name': self.name,
            'fields': self.fields,
        }
        if self.options:
            kwargs['options'] = self.options
        if self.bases and self.bases != (models.Model,):
            kwargs['bases'] = self.bases
        if self.managers and self.managers != [('objects', models.Manager())]:
            kwargs['managers'] = self.managers
        return (
            self.__class__.__name__,
            [],
            kwargs
        ) 
Example 7
Project: GetTogether   Author: GetTogetherComm   File: views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def to_representation(self, data):
        """
        List of object instances -> List of dicts of primitive datatypes.
        """
        # Dealing with nested relationships, data can be a Manager,
        # so, first get a queryset from the Manager if needed
        iterable = data.all() if isinstance(data, models.Manager) else data

        repr_data = OrderedDict(
            {
                "@context": "https://www.w3.org/ns/activitystreams",
                "summary": self.child.verbose_name_plural,
                "type": "Collection",
                "totalItems": len(iterable),
                "items": [self.child.to_representation(item) for item in iterable],
            }
        )
        repr_data.move_to_end("@context", last=False)
        repr_data.move_to_end("items")
        return repr_data 
Example 8
Project: openhgsenti   Author: drexly   File: models.py    License: Apache License 2.0 6 votes vote down vote up
def deconstruct(self):
        kwargs = {
            'name': self.name,
            'fields': self.fields,
        }
        if self.options:
            kwargs['options'] = self.options
        if self.bases and self.bases != (models.Model,):
            kwargs['bases'] = self.bases
        if self.managers and self.managers != [('objects', models.Manager())]:
            kwargs['managers'] = self.managers
        return (
            self.__class__.__name__,
            [],
            kwargs
        ) 
Example 9
Project: python2017   Author: bpgc-cte   File: models.py    License: MIT License 6 votes vote down vote up
def deconstruct(self):
        kwargs = {
            'name': self.name,
            'fields': self.fields,
        }
        if self.options:
            kwargs['options'] = self.options
        if self.bases and self.bases != (models.Model,):
            kwargs['bases'] = self.bases
        if self.managers and self.managers != [('objects', models.Manager())]:
            kwargs['managers'] = self.managers
        return (
            self.__class__.__name__,
            [],
            kwargs
        ) 
Example 10
Project: django-seeker   Author: imsweb   File: mapping.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def follow(obj, path, force_string=False):
    parts = path.split('__') if path else []
    for idx, part in enumerate(parts):
        if hasattr(obj, 'get_%s_display' % part):
            # If the root object has a method to get the display value for this part, we're done (the rest of the path,
            # if any, is ignored).
            return getattr(obj, 'get_%s_display' % part)()
        else:
            # Otherwise, follow the yellow brick road.
            obj = getattr(obj, part, None)
            if isinstance(obj, models.Manager):
                # Managers are a special case - basically, branch and recurse over all objects with the remainder of the
                # path. This means any path with a Manager/ManyToManyField in it will always return a list, which I
                # think makes sense.
                new_path = '__'.join(parts[idx + 1:])
                if new_path:
                    return [follow(o, new_path, force_string=True) for o in obj.all()]
    if force_string and isinstance(obj, models.Model):
        return six.text_type(obj)
    return obj 
Example 11
Project: django-seeker   Author: imsweb   File: mapping.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def serialize_object(obj, mapping, prepare=None):
    """
    Given a Django model instance and a ``elasticsearch_dsl.Mapping`` or ``elasticsearch_dsl.InnerObject``, returns a
    dictionary of field data that should be indexed.
    """
    data = {}
    for name in mapping:
        prep_func = getattr(prepare, 'prepare_%s' % name, None)
        if prep_func:
            data[name] = prep_func(obj)
        else:
            field = mapping[name]
            value = follow(obj, name)
            if value is not None:
                if isinstance(value, models.Model):
                    data[name] = serialize_object(value, field.properties) if isinstance(field, InnerObject) else six.text_type(value)
                elif isinstance(value, models.Manager):
                    if isinstance(field, InnerObject):
                        data[name] = [serialize_object(v, field.properties) for v in value.all()]
                    else:
                        data[name] = [six.text_type(v) for v in value.all()]
                else:
                    data[name] = value
    return data 
Example 12
Project: django-sqlserver   Author: denisenkom   File: test_state.py    License: MIT License 6 votes vote down vote up
def test_custom_default_manager_added_to_the_model_state(self):
        """
        When the default manager of the model is a custom manager,
        it needs to be added to the model state.
        """
        new_apps = Apps(['migrations'])
        custom_manager = models.Manager()

        class Author(models.Model):
            objects = models.TextField()
            authors = custom_manager

            class Meta:
                app_label = 'migrations'
                apps = new_apps

        project_state = ProjectState.from_apps(new_apps)
        author_state = project_state.models['migrations', 'author']
        self.assertEqual(author_state.managers, [('authors', custom_manager)]) 
Example 13
Project: django-sqlserver   Author: denisenkom   File: test_state.py    License: MIT License 6 votes vote down vote up
def test_custom_default_manager_named_objects_with_false_migration_flag(self):
        """
        When a manager is added with a name of 'objects' but it does not
        have `use_in_migrations = True`, no migration should be added to the
        model state (#26643).
        """
        new_apps = Apps(['migrations'])

        class Author(models.Model):
            objects = models.Manager()

            class Meta:
                app_label = 'migrations'
                apps = new_apps

        project_state = ProjectState.from_apps(new_apps)
        author_state = project_state.models['migrations', 'author']
        self.assertEqual(author_state.managers, []) 
Example 14
Project: django-sqlserver   Author: denisenkom   File: test_state.py    License: MIT License 6 votes vote down vote up
def test_custom_default_manager(self):
        new_apps = Apps(['migrations'])

        class Author(models.Model):
            manager1 = models.Manager()
            manager2 = models.Manager()

            class Meta:
                app_label = 'migrations'
                apps = new_apps
                default_manager_name = 'manager2'

        project_state = ProjectState.from_apps(new_apps)
        author_state = project_state.models['migrations', 'author']
        self.assertEqual(author_state.options['default_manager_name'], 'manager2')
        self.assertEqual(author_state.managers, [('manager2', Author.manager1)]) 
Example 15
Project: Dailyfresh-B2C   Author: BeanWei   File: representation.py    License: Apache License 2.0 6 votes vote down vote up
def smart_repr(value):
    if isinstance(value, models.Manager):
        return manager_repr(value)

    if isinstance(value, Promise) and value._delegate_text:
        value = force_text(value)

    value = unicode_repr(value)

    # Representations like u'help text'
    # should simply be presented as 'help text'
    if value.startswith("u'") and value.endswith("'"):
        return value[1:]

    # Representations like
    # <django.core.validators.RegexValidator object at 0x1047af050>
    # Should be presented as
    # <django.core.validators.RegexValidator object>
    value = re.sub(' at 0x[0-9A-Fa-f]{4,32}>', '>', value)

    return value 
Example 16
Project: djongo   Author: nesdis   File: test_state.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_custom_default_manager_added_to_the_model_state(self):
        """
        When the default manager of the model is a custom manager,
        it needs to be added to the model state.
        """
        new_apps = Apps(['migrations'])
        custom_manager = models.Manager()

        class Author(models.Model):
            objects = models.TextField()
            authors = custom_manager

            class Meta:
                app_label = 'migrations'
                apps = new_apps

        project_state = ProjectState.from_apps(new_apps)
        author_state = project_state.models['migrations', 'author']
        self.assertEqual(author_state.managers, [('authors', custom_manager)]) 
Example 17
Project: djongo   Author: nesdis   File: test_state.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_custom_default_manager_named_objects_with_false_migration_flag(self):
        """
        When a manager is added with a name of 'objects' but it does not
        have `use_in_migrations = True`, no migration should be added to the
        model state (#26643).
        """
        new_apps = Apps(['migrations'])

        class Author(models.Model):
            objects = models.Manager()

            class Meta:
                app_label = 'migrations'
                apps = new_apps

        project_state = ProjectState.from_apps(new_apps)
        author_state = project_state.models['migrations', 'author']
        self.assertEqual(author_state.managers, []) 
Example 18
Project: djongo   Author: nesdis   File: test_state.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_custom_default_manager(self):
        new_apps = Apps(['migrations'])

        class Author(models.Model):
            manager1 = models.Manager()
            manager2 = models.Manager()

            class Meta:
                app_label = 'migrations'
                apps = new_apps
                default_manager_name = 'manager2'

        project_state = ProjectState.from_apps(new_apps)
        author_state = project_state.models['migrations', 'author']
        self.assertEqual(author_state.options['default_manager_name'], 'manager2')
        self.assertEqual(author_state.managers, [('manager2', Author.manager1)]) 
Example 19
Project: aswan   Author: momosecurity   File: models.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_hit_log_model(db_table):
    class CustomMetaClass(ModelBase):
        def __new__(cls, name, bases, attrs):
            model = super(CustomMetaClass, cls).__new__(cls, name, bases,
                                                        attrs)
            model._meta.db_table = db_table
            model._meta.index_together = (
                ('time',),
                ('user_id',),
            )
            model.managed = False
            return model

    class HitLogModel(models.Model, metaclass=CustomMetaClass):
        time = models.DateTimeField(verbose_name=_(u'命中时间'))
        rule_id = models.IntegerField(verbose_name=_(u'规则ID'))
        user_id = models.IntegerField(verbose_name=_(u'命中用户'))
        kwargs = models.CharField(max_length=128, null=False, default='', verbose_name=_(u'扩展参数'))
        req_body = models.CharField(max_length=512, null=False, default='', verbose_name=_(u'请求参数'))
        control = models.CharField(max_length=16, null=False, default='', verbose_name=_(u'管控原子'))
        custom = models.CharField(max_length=50, null=False, default='', verbose_name=_(u'策略组解释'))
        group_name = models.CharField(max_length=256, null=False, default='',
                                      verbose_name=_(u'策略原子组名称'))
        group_uuid = models.CharField(max_length=36, null=False, default='',
                                      verbose_name=_(u'策略原子组UUID'))
        hit_number = models.PositiveSmallIntegerField(null=False, default=1, verbose_name=_(u'命中次序'))

        objects = Manager()

    return HitLogModel 
Example 20
Project: kobo-predict   Author: awemulya   File: models.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_staffs(self):
        staffs = self.project_roles.filter(
            group__name__in=["Reviewer", "Project Manager"])
        return staffs 
Example 21
Project: kobo-predict   Author: awemulya   File: models.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_staffs_both_role(self):
        managers_id = self.project_roles.filter(
            group__name="Project Manager").values_list('user__id', flat=True)
        reviewers_id = self.project_roles.filter(
            group__name="Reviewer").values_list('user__id', flat=True)
        both = list(set(managers_id).intersection(reviewers_id))
        return both 
Example 22
Project: hutils   Author: zaihui   File: databases.py    License: MIT License 5 votes vote down vote up
def filter_related(self, name: str, *, include_all=False, **conditions) -> "HQuerySet":
        """ 利用 FilteredRelation 优化 Query 的方法
        官方文档参见: https://docs.djangoproject.com/en/2.1/ref/models/querysets/#filteredrelation-objects

        还有一种写法是 Manager.from_queryset, 不过那样就没有 Pycharm Django 的补全和提示了,很不好
        https://docs.djangoproject.com/en/2.1/topics/db/managers/#calling-custom-queryset-methods-from-the-manager

        Examples::

            queryset = account.followers.filter(tags__name='rap', tags__deactivated_at__isnull=True)

        Equals to::

            queryset = account.followers.filter_related('tags', name='rap')

        :param name: Django related name
        :param include_all: True to include deactivated instances
        :param conditions: real filters
        """
        filtered_name = "filtered_{}".format(name)
        key, value = conditions.popitem()
        condition = {"{}__{}".format(filtered_name, key): value}
        if not include_all:
            conditions.setdefault("deactivated_at__isnull", True)
        conditions = {"{}__{}".format(name, k): v for k, v in conditions.items()}
        return self._queryset.annotate(**{filtered_name: FilteredRelation(name, condition=Q(**conditions))}).filter(
            **condition
        ) 
Example 23
Project: hutils   Author: zaihui   File: databases.py    License: MIT License 5 votes vote down vote up
def _queryset(self) -> "HQuerySet":
        if isinstance(self, models.Manager):
            return self.get_queryset()
        # noinspection PyTypeChecker
        return self 
Example 24
Project: bioforum   Author: reBiocoder   File: options.py    License: MIT License 5 votes vote down vote up
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 
Example 25
Project: corruption_tracker   Author: autogestion   File: serializers.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_representation(self, data):
        iterable = data.all() if isinstance(data, models.Manager) else data
        return [
            self.child.to_representation(item) for item in iterable if item
        ] 
Example 26
Project: corruption_tracker   Author: autogestion   File: serializers.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_representation(self, data):
        iterable = data.all() if isinstance(data, models.Manager) else data
        return [
            self.child.to_representation(item) for item in iterable if item
        ] 
Example 27
Project: django-cruds   Author: bmihelac   File: crud_tags.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def format_value(obj, field_name):
    """
    Simple value formatting.

    If value is model instance returns link to detail view if exists.
    """
    display_func = getattr(obj, 'get_%s_display' % field_name, None)
    if display_func:
        return display_func()
    value = getattr(obj, field_name)

    if isinstance(value, models.fields.files.FieldFile):
        if value:
            return mark_safe('<a href="%s">%s</a>' % (
                value.url,
                os.path.basename(value.name),
            ))
        else:
            return ''

    if isinstance(value, models.Model):
        return format_value_instance(value)

    if isinstance(value, models.Manager):
        return mark_safe(', '.join(
            [format_value_instance(instance) for instance in value.all()]
        ))
    if value is None:
        value = ""
    return value 
Example 28
Project: partisan-discourse   Author: DistrictDataLabs   File: managers.py    License: Apache License 2.0 5 votes vote down vote up
def democratic(self):
        """
        Filters the annotations for only democratic annotations.
        """
        return self.filter(label__slug='democratic')


##########################################################################
## Corpus Manager
########################################################################## 
Example 29
Project: Collaboration-System   Author: fresearchgroup   File: admin.py    License: GNU General Public License v2.0 5 votes vote down vote up
def compare(self, obj, version1, version2):
    def replace_taggit_field(version_ins):
        for fieldname in version_ins.field_dict:
            if isinstance(version_ins.field_dict[fieldname], Manager):
                version_ins.field_dict[fieldname] = []
    replace_taggit_field(version1)
    replace_taggit_field(version2)
    return _old_compare(self, obj, version1, version2) 
Example 30
Project: Collaboration-System   Author: fresearchgroup   File: admin.py    License: GNU General Public License v2.0 5 votes vote down vote up
def compare(self, obj, version1, version2):
    def replace_taggit_field(version_ins):
        for fieldname in version_ins.field_dict:
            if isinstance(version_ins.field_dict[fieldname], Manager):
                version_ins.field_dict[fieldname] = []
    replace_taggit_field(version1)
    replace_taggit_field(version2)
    return _old_compare(self, obj, version1, version2)