當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。