Python django.db.models.Manager() Examples

The following are 30 code examples of django.db.models.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 , or try the search function .
Example #1
Source File: test_state.py    From djongo with 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 #2
Source File: utils.py    From coursys with 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 #3
Source File: models.py    From bioforum with 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
Source File: utils.py    From django-rest-framework-json-api with 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
Source File: models.py    From GTDWeb with 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 #6
Source File: models.py    From Hands-On-Application-Development-with-PyCharm with 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 #7
Source File: models.py    From python with 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 #8
Source File: views.py    From GetTogether with 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 #9
Source File: models.py    From openhgsenti with 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 #10
Source File: models.py    From python2017 with 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 #11
Source File: mapping.py    From django-seeker with 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 #12
Source File: mapping.py    From django-seeker with 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 #13
Source File: test_state.py    From django-sqlserver with 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 #14
Source File: test_state.py    From django-sqlserver with 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 #15
Source File: test_state.py    From django-sqlserver with 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 #16
Source File: representation.py    From Dailyfresh-B2C with 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 #17
Source File: test_state.py    From djongo with 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 #18
Source File: test_state.py    From djongo with 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 #19
Source File: test_operations.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_create_model(self):
        """
        Tests the CreateModel operation.
        Most other tests use this operation as part of setup, so check failures here first.
        """
        operation = migrations.CreateModel(
            "Pony",
            [
                ("id", models.AutoField(primary_key=True)),
                ("pink", models.IntegerField(default=1)),
            ],
        )
        self.assertEqual(operation.describe(), "Create model Pony")
        # Test the state alteration
        project_state = ProjectState()
        new_state = project_state.clone()
        operation.state_forwards("test_crmo", new_state)
        self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony")
        self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2)
        # Test the database alteration
        self.assertTableNotExists("test_crmo_pony")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_crmo", editor, project_state, new_state)
        self.assertTableExists("test_crmo_pony")
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_crmo", editor, new_state, project_state)
        self.assertTableNotExists("test_crmo_pony")
        # And deconstruction
        definition = operation.deconstruct()
        self.assertEqual(definition[0], "CreateModel")
        self.assertEqual(definition[1], [])
        self.assertEqual(sorted(definition[2].keys()), ["fields", "name"])
        # And default manager not in set
        operation = migrations.CreateModel("Foo", fields=[], managers=[("objects", models.Manager())])
        definition = operation.deconstruct()
        self.assertNotIn('managers', definition[2]) 
Example #20
Source File: test_writer.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_serialize_managers(self):
        self.assertSerializedEqual(models.Manager())
        self.assertSerializedResultEqual(
            FoodQuerySet.as_manager(),
            ('migrations.models.FoodQuerySet.as_manager()', {'import migrations.models'})
        )
        self.assertSerializedEqual(FoodManager('a', 'b'))
        self.assertSerializedEqual(FoodManager('x', 'y', c=3, d=4)) 
Example #21
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_custom_base_manager(self):
        new_apps = Apps(['migrations'])

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

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

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

            class Meta:
                app_label = 'migrations'
                apps = new_apps
                base_manager_name = 'manager1'

        project_state = ProjectState.from_apps(new_apps)

        author_state = project_state.models['migrations', 'author']
        self.assertEqual(author_state.options['base_manager_name'], 'manager2')
        self.assertEqual(author_state.managers, [
            ('manager1', Author.manager1),
            ('manager2', Author.manager2),
        ])

        author2_state = project_state.models['migrations', 'author2']
        self.assertEqual(author2_state.options['base_manager_name'], 'manager1')
        self.assertEqual(author2_state.managers, [
            ('manager1', Author2.manager1),
        ]) 
Example #22
Source File: test_operations.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_create_model_with_duplicate_manager_name(self):
        with self.assertRaisesMessage(ValueError, 'Found duplicate value objects in CreateModel managers argument.'):
            migrations.CreateModel(
                "Pony",
                fields=[],
                managers=[
                    ("objects", models.Manager()),
                    ("objects", models.Manager()),
                ],
            ) 
Example #23
Source File: test_operations.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_alter_model_managers(self):
        """
        The managers on a model are set.
        """
        project_state = self.set_up_test_model("test_almoma")
        # Test the state alteration
        operation = migrations.AlterModelManagers(
            "Pony",
            managers=[
                ("food_qs", FoodQuerySet.as_manager()),
                ("food_mgr", FoodManager("a", "b")),
                ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)),
            ]
        )
        self.assertEqual(operation.describe(), "Change managers on Pony")
        managers = project_state.models["test_almoma", "pony"].managers
        self.assertEqual(managers, [])

        new_state = project_state.clone()
        operation.state_forwards("test_almoma", new_state)
        self.assertIn(("test_almoma", "pony"), new_state.models)
        managers = new_state.models["test_almoma", "pony"].managers
        self.assertEqual(managers[0][0], "food_qs")
        self.assertIsInstance(managers[0][1], models.Manager)
        self.assertEqual(managers[1][0], "food_mgr")
        self.assertIsInstance(managers[1][1], FoodManager)
        self.assertEqual(managers[1][1].args, ("a", "b", 1, 2))
        self.assertEqual(managers[2][0], "food_mgr_kwargs")
        self.assertIsInstance(managers[2][1], FoodManager)
        self.assertEqual(managers[2][1].args, ("x", "y", 3, 4))
        rendered_state = new_state.apps
        model = rendered_state.get_model('test_almoma', 'pony')
        self.assertIsInstance(model.food_qs, models.Manager)
        self.assertIsInstance(model.food_mgr, FoodManager)
        self.assertIsInstance(model.food_mgr_kwargs, FoodManager) 
Example #24
Source File: models.py    From ctf-gameserver with ISC License 5 votes vote down vote up
def get_queryset(self):
            return super().get_queryset().filter(category=None).exclude(title='')

    # The first Manager in a class is used as default 
Example #25
Source File: models.py    From ctf-gameserver with ISC License 5 votes vote down vote up
def get_queryset(self):
            return super().get_queryset().filter(nop_team=False)

    # The first Manager in a class is used as default 
Example #26
Source File: models.py    From ctf-gameserver with ISC License 5 votes vote down vote up
def get_queryset(self):
            return super().get_queryset().filter(category=None).exclude(title='')

    # The first Manager in a class is used as default 
Example #27
Source File: models.py    From ctf-gameserver with ISC License 5 votes vote down vote up
def get_queryset(self):
            return super().get_queryset().filter(category=None).exclude(title='')

    # The first Manager in a class is used as default 
Example #28
Source File: models.py    From ctf-gameserver with ISC License 5 votes vote down vote up
def get_queryset(self):
            return super().get_queryset().filter(nop_team=False)

    # The first Manager in a class is used as default 
Example #29
Source File: models.py    From ctf-gameserver with ISC License 5 votes vote down vote up
def get_queryset(self):
            return super().get_queryset().filter(category=None).exclude(title='')

    # The first Manager in a class is used as default 
Example #30
Source File: models.py    From ctf-gameserver with ISC License 5 votes vote down vote up
def get_queryset(self):
            return super().get_queryset().filter(category=None).exclude(title='')

    # The first Manager in a class is used as default