Python django.core.exceptions.MultipleObjectsReturned() Examples

The following are 30 code examples of django.core.exceptions.MultipleObjectsReturned(). 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.core.exceptions , or try the search function .
Example #1
Source File: document.py    From wagtail-markdown with zlib License 6 votes vote down vote up
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) 
Example #2
Source File: ajax.py    From dissemin with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: page.py    From wagtail-markdown with zlib License 6 votes vote down vote up
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) 
Example #4
Source File: management.py    From zulip with Apache License 2.0 6 votes vote down vote up
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}'") 
Example #5
Source File: __init__.py    From astrobin with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #6
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
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()
        ) 
Example #7
Source File: nir2email.py    From mrs with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #8
Source File: orm.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: REST_serializers.py    From YaraGuardian with Apache License 2.0 6 votes vote down vote up
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 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #11
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #12
Source File: set.py    From helfertool with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_gift_num(self, gift):
        try:
            tmp = IncludedGift.objects.get(gift_set=self, gift=gift)
            return tmp.count
        except (IncludedGift.DoesNotExist, MultipleObjectsReturned):
            return 0 
Example #13
Source File: test_utils.py    From bridge-adaptivity with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_choose_activity(self):
        try:
            # test if 2 activities has the same launch url but has different collections
            # this method should return only one activity, filtered by collection_order.order and sequence.collection
            chosen_activity = choose_activity(sequence=self.sequence)
        except MultipleObjectsReturned as e:
            log.error(Activity.ojbects.all().values('collection', 'source_launch_url'))
            self.fail(e)
        expected_activity = Activity.objects.get(
            collection=self.sequence.collection_order.collection, source_launch_url=f"{self.source_launch_url}5"
        )
        self.assertEqual(chosen_activity, expected_activity) 
Example #14
Source File: api_test.py    From micromasters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_social_auth(self):
        """
        Tests that get_social_auth returns a user's edX social auth object, and if multiple edX social auth objects
        exists, it raises an exception
        """
        assert get_social_auth(self.user) == self.user.social_auth.get(provider=EdxOrgOAuth2.name)
        UserSocialAuthFactory.create(user=self.user, uid='other name')
        with self.assertRaises(MultipleObjectsReturned):
            get_social_auth(self.user) 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_explicit_fk(self):
        # Create a new Article with get_or_create using an explicit value
        # for a ForeignKey.
        a2, created = Article.objects.get_or_create(
            headline="John's second test",
            pub_date=datetime.date(2011, 5, 7),
            reporter_id=self.r.id,
        )
        self.assertTrue(created)
        self.assertEqual(a2.reporter.id, self.r.id)

        # You can specify filters containing the explicit FK value.
        self.assertQuerysetEqual(
            Article.objects.filter(reporter_id__exact=self.r.id),
            ["<Article: John's second test>", "<Article: This is a test>"]
        )

        # Create an Article by Paul for the same date.
        a3 = Article.objects.create(
            headline="Paul's commentary",
            pub_date=datetime.date(2011, 5, 7),
            reporter_id=self.r2.id,
        )
        self.assertEqual(a3.reporter.id, self.r2.id)

        # Get should respect explicit foreign keys as well.
        msg = 'get() returned more than one Article -- it returned 2!'
        with self.assertRaisesMessage(MultipleObjectsReturned, msg):
            Article.objects.get(reporter_id=self.r.id)
        self.assertEqual(
            repr(a3),
            repr(Article.objects.get(reporter_id=self.r2.id, pub_date=datetime.date(2011, 5, 7)))
        ) 
Example #16
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_explicit_fk(self):
        # Create a new Article with get_or_create using an explicit value
        # for a ForeignKey.
        a2, created = Article.objects.get_or_create(
            headline="John's second test",
            pub_date=datetime.date(2011, 5, 7),
            reporter_id=self.r.id,
        )
        self.assertTrue(created)
        self.assertEqual(a2.reporter.id, self.r.id)

        # You can specify filters containing the explicit FK value.
        self.assertQuerysetEqual(
            Article.objects.filter(reporter_id__exact=self.r.id),
            ["<Article: John's second test>", "<Article: This is a test>"]
        )

        # Create an Article by Paul for the same date.
        a3 = Article.objects.create(
            headline="Paul's commentary",
            pub_date=datetime.date(2011, 5, 7),
            reporter_id=self.r2.id,
        )
        self.assertEqual(a3.reporter.id, self.r2.id)

        # Get should respect explicit foreign keys as well.
        msg = 'get() returned more than one Article -- it returned 2!'
        with self.assertRaisesMessage(MultipleObjectsReturned, msg):
            Article.objects.get(reporter_id=self.r.id)
        self.assertEqual(
            repr(a3),
            repr(Article.objects.get(reporter_id=self.r2.id, pub_date=datetime.date(2011, 5, 7)))
        ) 
Example #17
Source File: orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_exception_class(items):
    """Return exception class to raise.

    If `items` looks like a Django ORM result set, returns the
    `MultipleObjectsReturned` class as defined in that model.  Otherwise,
    returns the generic class.
    """
    model = getattr(items, "model", None)
    return getattr(model, "MultipleObjectsReturned", MultipleObjectsReturned) 
Example #18
Source File: orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_one(items, exception_class=None):
    """Assume there's at most one item in `items`, and return it (or None).

    If `items` contains more than one item, raise an error.  If `items` looks
    like a Django ORM result set, the error will be of the same model-specific
    Django `MultipleObjectsReturned` type that `items.get()` would raise.
    Otherwise, a plain Django :class:`MultipleObjectsReturned` error.

    :param items: Any sequence.
    :param exception_class: The exception class to raise if there is an error.
        If not specified, will use MultipleObjectsReturned (from the
        appropriate model class, if it can be determined).
    :return: The one item in that sequence, or None if it was empty.
    """
    # The only numbers we care about are zero, one, and "many."  Fetch
    # just enough items to distinguish between these.  Use islice so as
    # to support both sequences and iterators.
    retrieved_items = tuple(islice(items, 0, 2))
    length = len(retrieved_items)
    if length == 0:
        return None
    elif length == 1:
        return retrieved_items[0]
    else:
        if exception_class is None:
            exception_class = get_exception_class(items)
        object_name = get_model_object_name(items)
        if object_name is None:
            object_name = "item"
        raise exception_class("Got more than one %s." % object_name.lower()) 
Example #19
Source File: test_orm.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_one_raises_model_error_if_query_result_is_too_big(self):
        self.assertRaises(
            FakeModel.MultipleObjectsReturned,
            get_one,
            FakeQueryResult(FakeModel, list(range(2))),
        ) 
Example #20
Source File: utilities.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_active_app(request=None, url=None, get_class=None):
    """
    Get the active TethysApp object based on the request or URL.
    """
    from tethys_apps.models import TethysApp
    apps_root = 'apps'

    if request is not None:
        the_url = request.path
    elif url is not None:
        the_url = url
    else:
        return None

    url_parts = the_url.split('/')
    app = None

    # Find the app key
    if apps_root in url_parts:
        # The app root_url is the path item following (+1) the apps_root item
        app_root_url_index = url_parts.index(apps_root) + 1
        app_root_url = url_parts[app_root_url_index]

        if app_root_url:
            try:
                # Get the app from the database
                app = TethysApp.objects.get(root_url=app_root_url)
            except ObjectDoesNotExist:
                tethys_log.warning('Could not locate app with root url "{0}".'.format(app_root_url))
            except MultipleObjectsReturned:
                tethys_log.warning('Multiple apps found with root url "{0}".'.format(app_root_url))

    if get_class:
        app = get_app_class(app)

    return app 
Example #21
Source File: facade_v1.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def get_or_create_healthcheck(user, healthcheck_expect, healthcheck_type, healthcheck_request, healthcheck_destination, identifier=''):
    try:
        # Query HealthCheck table for one equal this
        if identifier == '':
            hc = Healthcheck.objects.get(healthcheck_expect=healthcheck_expect, healthcheck_type=healthcheck_type,
                                         healthcheck_request=healthcheck_request, destination=healthcheck_destination)
        else:
            hc = Healthcheck.objects.get(identifier=identifier, healthcheck_expect=healthcheck_expect, healthcheck_type=healthcheck_type,
                                         healthcheck_request=healthcheck_request, destination=healthcheck_destination)

    # Else, add a new one
    except ObjectDoesNotExist:
        hc = Healthcheck(identifier=identifier, healthcheck_type=healthcheck_type, healthcheck_request=healthcheck_request,
                         healthcheck_expect=healthcheck_expect, destination=healthcheck_destination)
        hc.save()

    # Get the fisrt occureny and warn if redundant HCs are present
    except MultipleObjectsReturned:
        log.warning(
            'Multiple healthcheck entries found for the given parameters')
        if identifier == '':
            hc = Healthcheck.objects.filter(healthcheck_expect=healthcheck_expect, healthcheck_type=healthcheck_type,
                                            healthcheck_request=healthcheck_request, destination=healthcheck_destination).order_by('id')[0]
        else:
            hc = Healthcheck.objects.filter(identifier=identifier, healthcheck_expect=healthcheck_expect, healthcheck_type=healthcheck_type,
                                            healthcheck_request=healthcheck_request, destination=healthcheck_destination).order_by('id')[0]

    return hc 
Example #22
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #23
Source File: write.py    From django-cachalot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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') 
Example #24
Source File: protocol.py    From dissemin with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #25
Source File: mail.py    From prospector with GNU General Public License v3.0 5 votes vote down vote up
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] 
Example #26
Source File: models.py    From prospector with GNU General Public License v3.0 5 votes vote down vote up
def update_id(self):
        """
        Set .id so that we update existing entries if a score tree already
        exists.
        """
        # .id is already set, so don't do anything
        if self.id is not None:
            return

        try:
            self.id = type(self).objects.get(project=self.project,
                                             metric=self.metric,
                                             start=self.start,
                                             end=self.end).id
        except type(self).DoesNotExist:
            pass

        except MultipleObjectsReturned:
            logger.warn("Duplicate MetricCache scores found in the database "
                        "matching (%s, %s, %s, %s). "
                        "Picking the first one...",
                        self.project, self.metric, self.start, self.end)

            self.id = type(self).objects.filter(project=self.project,
                                                metric=self.metric,
                                                start=self.start,
                                                end=self.end)[:1][0].id 
Example #27
Source File: serializers.py    From lego with MIT License 5 votes vote down vote up
def to_internal_value(self, data):
        try:
            return string_to_instance(data)
        except (TypeError, ValueError):
            self.fail("incorrect_type")
        except ObjectDoesNotExist:
            self.fail("does_not_exist", data=data)
        except MultipleObjectsReturned:
            self.fail("multiple_objects_returned") 
Example #28
Source File: models.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def validate(self):
        """Validates whether Environment is already associated with EnvironmentVip

            @raise EnvironmentEnvironmentVipDuplicatedError: if Environment is already associated with EnvironmentVip
        """
        try:
            EnvironmentEnvironmentVip.objects.get(
                environment=self.environment,
                environment_vip=self.environment_vip)
        except ObjectDoesNotExist:
            pass
        except MultipleObjectsReturned:
            raise EnvironmentEnvironmentVipDuplicatedError(
                None, u'Environment already registered for the environment vip.') 
Example #29
Source File: models.py    From helfertool with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_exclusive_user(self, event):
        if self.inventory.multiple_assignments:
            return None

        try:
            return UsedItem.objects.get(item=self, helper__event=event,
                                        timestamp_returned=None).helper
        except UsedItem.DoesNotExist:
            raise NotAssigned
        except MultipleObjectsReturned:
            raise InvalidMultipleAssignment() 
Example #30
Source File: 0019_auto_20180730_0211.py    From eventoL with GNU General Public License v3.0 5 votes vote down vote up
def set_owner_defaults(apps, schema_editor):
    Activity = apps.get_model('manager', 'Activity')
    EventUser = apps.get_model('manager', 'EventUser')
    User = apps.get_model(settings.AUTH_USER_MODEL)
    qs = Activity.objects.filter(owner=None)

    for activity in qs:
        email = activity.speaker_contact
        username = "{}-{}".format(email.split("@")[0], get_random_string(4))
        password = make_password(None)
        defaults = {'username': username, 'password': password}
        try:
            user, created = User.objects.get_or_create(email=email, defaults=defaults)
            if created:
                print("new user created: {}, (activity: {})".format(user.email, activity.title))
        except MultipleObjectsReturned:
            print("Multiple EventUser returned: {}, (activity: {})".format(user, activity.title))
            user = User.objects.filter(email=email).first()
        # get a EventUser
        try:
            event_user, created = EventUser.objects.get_or_create(
                user=user, defaults={'event': activity.event})
            if created:
                print("new EventUser created: {}, (activity: {})".format(event_user, activity.title))
        except MultipleObjectsReturned:
            print("Multiple EventUser returned: {}, (activity: {})".format(user, activity.title))
            event_user = EventUser.objects.filter(user=user).first()
        activity.owner = event_user
        activity.save()