From 77aacee6ed993d94bd83368e720004e8aff89c3c Mon Sep 17 00:00:00 2001 From: Kyle McCormick Date: Thu, 5 Sep 2019 14:53:55 -0400 Subject: [PATCH] Add query util read_replica_or_default() This is similar to use_read_replica_if_available(), but it just returns either 'read_replica' or 'default', for use with the Django ORM using() method. Syntactically, it fits nicer with queryset method-call chains. --- common/djangoapps/util/query.py | 39 ++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/common/djangoapps/util/query.py b/common/djangoapps/util/query.py index 865f0aee9f..535c113eeb 100644 --- a/common/djangoapps/util/query.py +++ b/common/djangoapps/util/query.py @@ -4,9 +4,46 @@ from __future__ import absolute_import from django.conf import settings +_READ_REPLICA_DB_ALIAS = "read_replica" + + def use_read_replica_if_available(queryset): """ If there is a database called 'read_replica', use that database for the queryset / manager. + + Example usage: + queryset = use_read_replica_if_available(SomeModel.objects.filter(...)) + + Arguments: + queryset (QuerySet) + + Returns: QuerySet """ - return queryset.using("read_replica") if "read_replica" in settings.DATABASES else queryset + return ( + queryset.using(_READ_REPLICA_DB_ALIAS) + if _READ_REPLICA_DB_ALIAS in settings.DATABASES + else queryset + ) + + +def read_replica_or_default(): + """ + If there is a database called "read_replica", + return "read_replica", otherwise return "default". + + This function is similiar to `use_read_replica_if_available`, + but is be more syntactically convenient for method call chaining. + Also, it always falls back to "default", + no matter what the queryset was using before. + + Example usage: + queryset = SomeModel.objects.filter(...).using(read_replica_or_default()) + + Returns: str + """ + return ( + _READ_REPLICA_DB_ALIAS + if _READ_REPLICA_DB_ALIAS in settings.DATABASES + else "default" + )