当前位置: 首页>>代码示例>>Python>>正文


Python models.Manager方法代码示例

本文整理汇总了Python中django.db.models.Manager方法的典型用法代码示例。如果您正苦于以下问题:Python models.Manager方法的具体用法?Python models.Manager怎么用?Python models.Manager使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.models的用法示例。


在下文中一共展示了models.Manager方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_object_or_None

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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 
开发者ID:sfu-fas,项目名称:coursys,代码行数:20,代码来源:utils.py

示例2: deconstruct

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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
        ) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:models.py

示例3: deconstruct

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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
        ) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:18,代码来源:models.py

示例4: get_relation_instance

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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 
开发者ID:django-json-api,项目名称:django-rest-framework-json-api,代码行数:18,代码来源:utils.py

示例5: to_representation

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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 
开发者ID:GetTogetherComm,项目名称:GetTogether,代码行数:22,代码来源:views.py

示例6: follow

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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 
开发者ID:imsweb,项目名称:django-seeker,代码行数:22,代码来源:mapping.py

示例7: serialize_object

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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 
开发者ID:imsweb,项目名称:django-seeker,代码行数:26,代码来源:mapping.py

示例8: test_custom_default_manager_added_to_the_model_state

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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)]) 
开发者ID:denisenkom,项目名称:django-sqlserver,代码行数:21,代码来源:test_state.py

示例9: test_custom_default_manager_named_objects_with_false_migration_flag

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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, []) 
开发者ID:denisenkom,项目名称:django-sqlserver,代码行数:20,代码来源:test_state.py

示例10: test_custom_default_manager

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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)]) 
开发者ID:denisenkom,项目名称:django-sqlserver,代码行数:18,代码来源:test_state.py

示例11: smart_repr

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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 
开发者ID:BeanWei,项目名称:Dailyfresh-B2C,代码行数:23,代码来源:representation.py

示例12: get_hit_log_model

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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 
开发者ID:momosecurity,项目名称:aswan,代码行数:32,代码来源:models.py

示例13: get_staffs

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
def get_staffs(self):
        staffs = self.project_roles.filter(
            group__name__in=["Reviewer", "Project Manager"])
        return staffs 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:6,代码来源:models.py

示例14: get_staffs_both_role

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:9,代码来源:models.py

示例15: filter_related

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Manager [as 别名]
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
        ) 
开发者ID:zaihui,项目名称:hutils,代码行数:30,代码来源:databases.py


注:本文中的django.db.models.Manager方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。