Python django.core.exceptions.MultipleObjectsReturned() Examples

The following are 30 code examples for showing how to use django.core.exceptions.MultipleObjectsReturned(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.core.exceptions , or try the search function .

Example 1
Project: dissemin   Author: dissemin   File: ajax.py    License: 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 2
Project: zulip   Author: zulip   File: management.py    License: 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 3
Project: mrs   Author: betagouv   File: nir2email.py    License: 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 4
Project: YaraGuardian   Author: PUNCH-Cyber   File: REST_serializers.py    License: 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 5
Project: djongo   Author: nesdis   File: tests.py    License: 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 6
Project: djongo   Author: nesdis   File: tests.py    License: 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 7
Project: maas   Author: maas   File: orm.py    License: 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 8
Project: maas   Author: maas   File: test_orm.py    License: 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 9
Project: astrobin   Author: astrobin   File: __init__.py    License: 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 10
Project: wagtail-markdown   Author: torchbox   File: page.py    License: 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 11
Project: wagtail-markdown   Author: torchbox   File: document.py    License: 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 12
Project: seqr   Author: macarthur-lab   File: variant_search_api.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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)
        }
    }) 
Example 13
Project: coursys   Author: sfu-fas   File: views.py    License: 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 14
Project: django-cachalot   Author: noripyt   File: write.py    License: 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 15
Project: dissemin   Author: dissemin   File: protocol.py    License: 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 16
Project: prospector   Author: chaoss   File: mail.py    License: 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 17
Project: prospector   Author: chaoss   File: models.py    License: 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 18
Project: lego   Author: webkom   File: serializers.py    License: 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 19
Project: GloboNetworkAPI   Author: globocom   File: models.py    License: 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 20
Project: GloboNetworkAPI   Author: globocom   File: facade_v1.py    License: 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 21
Project: eventoL   Author: eventoL   File: 0019_auto_20180730_0211.py    License: 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() 
Example 22
Project: Cinema   Author: ArnaudLevaufre   File: views.py    License: MIT License 5 votes vote down vote up
def watch(request, mid):
    try:
        ctx = {
            'movie': get_object_or_404(Movie, pk=mid),
        }
    except MultipleObjectsReturned:
        ctx = {
            'movie': Movie.objects.filter(pk=mid).first(),
        }
    return render(request, 'watch.html', ctx) 
Example 23
Project: ecommerce   Author: edx   File: paypal.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_basket(self, payment_id):
        """
        Retrieve a basket using a payment ID.

        Arguments:
            payment_id: payment_id received from PayPal.

        Returns:
            It will return related basket or log exception and return None if
            duplicate payment_id received or any other exception occurred.

        """
        try:
            basket = PaymentProcessorResponse.objects.get(
                processor_name=self.payment_processor.NAME,
                transaction_id=payment_id
            ).basket
            basket.strategy = strategy.Default()

            # TODO: Remove as a part of REVMI-124 as this is a hacky solution
            # The problem is that orders are being created after payment processing, and the discount is not
            # saved in the database, so it needs to be calculated again in order to save the correct info to the
            # order. REVMI-124 will create the order before payment processing, when we have the discount context.
            self._add_dynamic_discount_to_request(basket)
            # END TODO

            Applicator().apply(basket, basket.owner, self.request)

            basket_add_organization_attribute(basket, self.request.GET)
            return basket
        except MultipleObjectsReturned:
            logger.warning(u"Duplicate payment ID [%s] received from PayPal.", payment_id)
            return None
        except Exception:  # pylint: disable=broad-except
            logger.exception(u"Unexpected error during basket retrieval while executing PayPal payment.")
            return None 
Example 24
Project: django-sqlserver   Author: denisenkom   File: tests.py    License: MIT License 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.
        with self.assertRaises(MultipleObjectsReturned):
            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 25
Project: bridge-adaptivity   Author: harvard-vpal   File: test_utils.py    License: 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 26
Project: openstax-cms   Author: openstax   File: api.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def detail_view(self, request, pk=None, slug=None):
        param = pk
        if slug is not None:
            self.lookup_field = 'slug'
            param = slug
        try:
            return super().detail_view(request, param)
        except MultipleObjectsReturned:
            # Redirect to the listing view, filtered by the relevant slug
            # The router is registered with the `wagtailapi` namespace,
            # `pages` is our endpoint namespace and `listing` is the listing view url name.
            return redirect(
                reverse('wagtailapi:pages:listing') + f'?{self.lookup_field}={param}'
            ) 
Example 27
Project: helfertool   Author: helfertool   File: models.py    License: 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 28
Project: helfertool   Author: helfertool   File: set.py    License: 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 29
Project: micromasters   Author: mitodl   File: api_test.py    License: 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 30
Project: djongo   Author: nesdis   File: tests.py    License: 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)))
        )