#16281: ContentType.get_object_for_this_type using wrong database for creating
object
-------------------------------------+-------------------------------------
Reporter: tfrydrychewicz@… | Owner: (none)
Type: Bug | Status: new
Component: | Version: dev
contrib.contenttypes |
Severity: Normal | Resolution:
Keywords: contenttype, object | Triage Stage: Accepted
get_object_for_this_type, |
database, multiple |
Has patch: 1 | Needs documentation: 0
Needs tests: 1 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by bcail):
Here's a similar patch that does the current query, and if it fails, falls
back to the using the default router. This passes the tests if I fix the
number of expected queries in one test. If we go this direction, we'd
probably want to update the `get_all_objects_for_this_type` method as
well.
{{{
diff --git a/django/contrib/contenttypes/models.py
b/django/contrib/contenttypes/models.py
index 0d98ed3a4d..2cf08bc85e 100644
--- a/django/contrib/contenttypes/models.py
+++ b/django/contrib/contenttypes/models.py
@@ -2,7 +2,7 @@ from collections import defaultdict
from django.apps import apps
from django.db import models
-from django.db.models import Q
+from django.db.models import ObjectDoesNotExist, Q
from django.utils.translation import gettext_lazy as _
@@ -181,7 +181,10 @@ class ContentType(models.Model):
method. The ObjectNotExist exception, if thrown, will not be
caught,
so code that calls this method should catch it.
"""
- return
self.model_class()._base_manager.using(self._state.db).get(**kwargs)
+ try:
+ return
self.model_class()._base_manager.using(self._state.db).get(**kwargs)
+ except ObjectDoesNotExist:
+ return self.model_class()._base_manager.get(**kwargs)
def get_all_objects_for_this_type(self, **kwargs):
"""
diff --git a/tests/contenttypes_tests/test_fields.py
b/tests/contenttypes_tests/test_fields.py
index 5510f34cd0..dd1edae834 100644
--- a/tests/contenttypes_tests/test_fields.py
+++ b/tests/contenttypes_tests/test_fields.py
@@ -32,7 +32,7 @@ class GenericForeignKeyTests(TestCase):
Question.objects.all().delete()
post = Post.objects.get(pk=post.pk)
- with self.assertNumQueries(1):
+ with self.assertNumQueries(2):
self.assertEqual(post.object_id, question_pk)
self.assertIsNone(post.parent)
self.assertIsNone(post.parent)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/16281#comment:20>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/0107018bd3db5551-fea37b7e-c9b4-45a1-9f2b-1ff70a953acb-000000%40eu-central-1.amazonses.com.