Fixed #33501 -- Made order_with_respect_to respect database routers.

This commit is contained in:
Damian Posener 2022-02-07 15:06:25 +00:00 committed by Mariusz Felisiak
parent 2d472ad05c
commit 09e499a39e
2 changed files with 14 additions and 3 deletions

View File

@ -17,7 +17,6 @@ from django.core.exceptions import (
ValidationError, ValidationError,
) )
from django.db import ( from django.db import (
DEFAULT_DB_ALIAS,
DJANGO_VERSION_PICKLE_KEY, DJANGO_VERSION_PICKLE_KEY,
DatabaseError, DatabaseError,
connection, connection,
@ -2370,8 +2369,6 @@ class Model(metaclass=ModelBase):
def method_set_order(self, ordered_obj, id_list, using=None): def method_set_order(self, ordered_obj, id_list, using=None):
if using is None:
using = DEFAULT_DB_ALIAS
order_wrt = ordered_obj._meta.order_with_respect_to order_wrt = ordered_obj._meta.order_with_respect_to
filter_args = order_wrt.get_forward_related_filter(self) filter_args = order_wrt.get_forward_related_filter(self)
ordered_obj.objects.db_manager(using).filter(**filter_args).bulk_update( ordered_obj.objects.db_manager(using).filter(**filter_args).bulk_update(

View File

@ -6,6 +6,8 @@ from operator import attrgetter
class BaseOrderWithRespectToTests: class BaseOrderWithRespectToTests:
databases = {"default", "other"}
# Hook to allow subclasses to run these tests with alternate models. # Hook to allow subclasses to run these tests with alternate models.
Answer = None Answer = None
Post = None Post = None
@ -108,3 +110,15 @@ class BaseOrderWithRespectToTests:
a1.delete() a1.delete()
new_answer = self.Answer.objects.create(text="Black", question=q1) new_answer = self.Answer.objects.create(text="Black", question=q1)
self.assertSequenceEqual(q1.answer_set.all(), [a2, a4, new_answer]) self.assertSequenceEqual(q1.answer_set.all(), [a2, a4, new_answer])
def test_database_routing(self):
class WriteToOtherRouter:
def db_for_write(self, model, **hints):
return "other"
with self.settings(DATABASE_ROUTERS=[WriteToOtherRouter()]):
with self.assertNumQueries(0, using="default"), self.assertNumQueries(
1,
using="other",
):
self.q1.set_answer_order([3, 1, 2, 4])