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


Python exceptions.MultipleObjectsReturned方法代码示例

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


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

示例1: todo_list_add

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def todo_list_add(request):
    """
    Adds a paper from a users todolist
    """
    body = {
        'success_msg' : _('Remove from to-do list'),
        'error_msg' : _('Marking failed'),
        'data-action': 'unmark',
    }
    paper_pk = request.POST.get('paper_pk', None)
    if paper_pk is None:
        return body, 400
    try:
        paper = Paper.objects.get(pk=int(paper_pk))
    except (ObjectDoesNotExist, MultipleObjectsReturned, ValueError):
        return body, 404

    try:
        paper.todolist.add(request.user)
    except Exception as e:
        logger.exception(e)
        return body, 500

    return body, 200 
开发者ID:dissemin,项目名称:dissemin,代码行数:26,代码来源:ajax.py

示例2: get_user

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def get_user(self, email: str, realm: Optional[Realm]) -> UserProfile:

        # If a realm is specified, try to find the user there, and
        # throw an error if they don't exist.
        if realm is not None:
            try:
                return UserProfile.objects.select_related().get(
                    delivery_email__iexact=email.strip(), realm=realm)
            except UserProfile.DoesNotExist:
                raise CommandError(f"The realm '{realm}' does not contain a user with email '{email}'")

        # Realm is None in the remaining code path.  Here, we
        # optimistically try to see if there is exactly one user with
        # that email; if so, we'll return it.
        try:
            return UserProfile.objects.select_related().get(delivery_email__iexact=email.strip())
        except MultipleObjectsReturned:
            raise CommandError("This Zulip server contains multiple users with that email " +
                               "(in different realms); please pass `--realm` "
                               "to specify which one to modify.")
        except UserProfile.DoesNotExist:
            raise CommandError(f"This Zulip server does not contain a user with email '{email}'") 
开发者ID:zulip,项目名称:zulip,代码行数:24,代码来源:management.py

示例3: parse_nirs

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def parse_nirs(nirs):
    emails = []

    for nir in nirs:
        if nir:
            email = ""

            try:
                email = get_email(nir)

            except ObjectDoesNotExist:
                pass
            except MultipleObjectsReturned:
                p = Person.objects.filter(nir=nir).first()
                email = p.email or ""

            emails.append("{}; {};".format(nir, email))

    return emails 
开发者ID:betagouv,项目名称:mrs,代码行数:21,代码来源:nir2email.py

示例4: get_dependencies

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def get_dependencies(self, obj):
        dependencies = {'count': 0,
                        'available': [],
                        'missing': []}

        for dependency_name in obj.dependencies:
            try:
                dependency_rule = YaraRule.objects.get(name=dependency_name, owner=obj.owner)
                dependencies['available'].append(dependency_rule.name)
                # Use to return full dependency content, but we might just do name list for now
                # dependencies['available'][dependency_rule.name] = dependency_rule.format_rule()

            except MultipleObjectsReturned:
               dependency_rule =  YaraRule.objects.filter(name=dependency_name, owner=obj.owner)[0]
               dependencies['available'].append(dependency_rule.name)

            except ObjectDoesNotExist:
                dependencies['missing'].append(dependency_name)

            dependencies['count'] += 1

        return dependencies 
开发者ID:PUNCH-Cyber,项目名称:YaraGuardian,代码行数:24,代码来源:REST_serializers.py

示例5: test_too_many

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def test_too_many(self):
        # Create a very similar object
        a = Article(
            id=None,
            headline='Swallow bites Python',
            pub_date=datetime(2005, 7, 28),
        )
        a.save()

        self.assertEqual(Article.objects.count(), 2)

        # Django raises an Article.MultipleObjectsReturned exception if the
        # lookup matches more than one object
        msg = "get() returned more than one Article -- it returned 2!"
        with self.assertRaisesMessage(MultipleObjectsReturned, msg):
            Article.objects.get(headline__startswith='Swallow',)
        with self.assertRaisesMessage(MultipleObjectsReturned, msg):
            Article.objects.get(pub_date__year=2005,)
        with self.assertRaisesMessage(MultipleObjectsReturned, msg):
            Article.objects.get(pub_date__year=2005, pub_date__month=7) 
开发者ID:nesdis,项目名称:djongo,代码行数:22,代码来源:tests.py

示例6: get_object_by_specifiers_or_raise

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def get_object_by_specifiers_or_raise(self, specifiers, **kwargs):
        """Gets an object using the given specifier(s).

        If the specifier is empty, raises Http400.
        If multiple objects are returned, raises Http403.
        If the object cannot be found, raises Http404.

        :param:specifiers: unicode
        """
        object_name = get_model_object_name(self)
        if isinstance(specifiers, str):
            specifiers = specifiers.strip()
        if specifiers is None or specifiers == "":
            raise MAASAPIBadRequest("%s specifier required." % object_name)
        try:
            object = get_one(self.filter_by_specifiers(specifiers, **kwargs))
            if object is None:
                raise Http404("No %s matches the given query." % object_name)
        except self.model.MultipleObjectsReturned:
            raise MAASAPIForbidden(
                "Too many %s objects match the given query." % object_name
            )
        return object 
开发者ID:maas,项目名称:maas,代码行数:25,代码来源:orm.py

示例7: test_get_one_does_not_iterate_long_sequence_indefinitely

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def test_get_one_does_not_iterate_long_sequence_indefinitely(self):
        # Avoid typical performance pitfall of retrieving all objects.
        # In rare failure cases, there may be large numbers.  Fail fast.

        class InfinityException(Exception):
            """Iteration went on indefinitely."""

        def infinite_sequence():
            """Generator: count to infinity (more or less), then fail."""
            for counter in range(3):
                yield counter
            raise InfinityException()

        # Raises MultipleObjectsReturned as spec'ed.  It does not
        # iterate to infinity first!
        self.assertRaises(
            MultipleObjectsReturned, get_one, infinite_sequence()
        ) 
开发者ID:maas,项目名称:maas,代码行数:20,代码来源:test_orm.py

示例8: get_or_create_location

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def get_or_create_location(prop, value):
    k = None
    created = False

    try:
        return Location.objects.get(id=value)
    except ValueError:
        pass

    try:
        k, created = Location.objects.get_or_create(**{prop: value})
    except MultipleObjectsReturned:
        k = Location.objects.filter(**{prop: value})[0]

    if created:
        k.user_generated = True
        k.save()

    return k 
开发者ID:astrobin,项目名称:astrobin,代码行数:21,代码来源:__init__.py

示例9: run

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def run(self, name, optstr):
        try:
            text = name
            if optstr:
                text = optstr[0]

            page = Page.objects.get(title=name)
            url = page.url
            a = etree.Element('a')
            a.set('href', url)
            a.text = text
            return a
        except ObjectDoesNotExist:
            return '[page "{}" not found]'.format(name)
        except MultipleObjectsReturned:
            return '[multiple pages "{}" found]'.format(name) 
开发者ID:torchbox,项目名称:wagtail-markdown,代码行数:18,代码来源:page.py

示例10: run

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def run(self, name, optstr):
        try:
            text = name
            if len(optstr):
                text = optstr[0]

            doc = Document.objects.get(title=name)
            url = doc.url
            a = etree.Element('a')
            a.set('href', url)
            a.text = text
            return a
        except ObjectDoesNotExist:
            return '[document "{}" not found]'.format(name)
        except MultipleObjectsReturned:
            return '[multiple documents "{}" found]'.format(name) 
开发者ID:torchbox,项目名称:wagtail-markdown,代码行数:18,代码来源:document.py

示例11: create_saved_search_handler

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def create_saved_search_handler(request):
    request_json = json.loads(request.body)
    name = request_json.pop('name', None)
    if not name:
        return create_json_response({}, status=400, reason='"Name" is required')

    if (request_json.get('inheritance') or {}).get('filter', {}).get('genotype'):
        return create_json_response({}, status=400, reason='Saved searches cannot include custom genotype filters')

    try:
        saved_search, _ = VariantSearch.objects.get_or_create(
            search=request_json,
            created_by=request.user,
        )
    except MultipleObjectsReturned:
        # Can't create a unique constraint on JSON field, so its possible that a duplicate gets made by accident
        dup_searches = VariantSearch.objects.filter(
            search=request_json,
            created_by=request.user,
        ).order_by('created_date')
        saved_search = dup_searches[0]
        for search in dup_searches:
            search.delete()
    saved_search.name = name
    saved_search.save()

    return create_json_response({
        'savedSearchesByGuid': {
            saved_search.guid: get_json_for_saved_search(saved_search, request.user)
        }
    }) 
开发者ID:macarthur-lab,项目名称:seqr,代码行数:33,代码来源:variant_search_api.py

示例12: _userToFormFiller

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def _userToFormFiller(user):
    try:
        form_filler = FormFiller.objects.get(sfuFormFiller=user)
    except ObjectDoesNotExist:
        form_filler = FormFiller.objects.create(sfuFormFiller=user)
    except MultipleObjectsReturned:
        #  It shouldn't be possible, but there are occasionally Formfillers that have the same sfuFormFiller.  Since
        #  this isn't enforced at the database level, deal with it this way until we clean it up and/or enforce it.
        form_filler = FormFiller.objects.filter(sfuFormFiller=user).first()
    return form_filler 
开发者ID:sfu-fas,项目名称:coursys,代码行数:12,代码来源:views.py

示例13: test_invalidate_get

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def test_invalidate_get(self):
        with self.assertNumQueries(1):
            with self.assertRaises(Test.DoesNotExist):
                Test.objects.get(name='test')

        Test.objects.create(name='test')

        with self.assertNumQueries(1):
            Test.objects.get(name='test')

        Test.objects.create(name='test')

        with self.assertNumQueries(1):
            with self.assertRaises(MultipleObjectsReturned):
                Test.objects.get(name='test') 
开发者ID:noripyt,项目名称:django-cachalot,代码行数:17,代码来源:write.py

示例14: get_form_initial_data

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def get_form_initial_data(self, **kwargs):
        """
        Calls super and returns form's initial values.
        """
        data = super().get_form_initial_data(**kwargs)
        if self.paper.abstract:
            data['abstract'] = kill_html(self.paper.abstract)
        else:
            self.paper.consolidate_metadata(wait=False)

        # We try to find an email, if we do not succed, that's ok
        up = UserPreferences.get_by_user(user=self.user)
        if up.email:
            data['email'] = up.email
        else:
            try:
                r = Researcher.objects.get(user=self.user)
            except ObjectDoesNotExist:
                pass
            except MultipleObjectsReturned:
                logger.warning("User with id {} has multiple researcher objects assigned".format(self.user.id))
            else:
                if r.email:
                    data['email'] = r.email

        return data 
开发者ID:dissemin,项目名称:dissemin,代码行数:28,代码来源:protocol.py

示例15: get_participant

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import MultipleObjectsReturned [as 别名]
def get_participant(name, email):
    """
    name: String containing name of participant
    email: String containing email of participant

    Get hmeter_frontend.models.Participant object or create one with
    corresponding ParticipantEmail
    """
    if not email:
        try:
            return Participant.objects \
                              .filter(names__name=name,
                                      email_addresses__isnull=True)[:1][0]

        except IndexError:
            part = Participant.objects.create()
            part.names.create(name=name)
            return part

    try:
        return EmailAddress.objects.get(address=email).owner

    except EmailAddress.DoesNotExist:
        part = Participant.objects.create()
        part.names.create(name=name)
        EmailAddress.objects.create(address=email, owner=part)
        return part

    except MultipleObjectsReturned:
        logger.warn("Multiple email addresses found matching %s. "
                    "Refining query to include name.. (%s, %s)", email,
                    name, email,
                    exc_info=True)

        return EmailAddress.objects.filter(
            address=email, owner__names__name=name)[:1][0] 
开发者ID:chaoss,项目名称:prospector,代码行数:38,代码来源:mail.py


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