Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automaticaly select database when call transaction.on_commit #124

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions django_lifecycle/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Any, List

from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist
from django.db import transaction
from django.db import transaction, router
from django.utils.functional import cached_property

from . import NotSet
Expand Down Expand Up @@ -45,7 +45,10 @@ def run(self, instance: Any) -> None:
# to ensure it's available to execute later.
_on_commit_func = partial(self.method, instance)
_on_commit_func.__name__ = self.name
transaction.on_commit(_on_commit_func)
transaction.on_commit(
_on_commit_func,
using=router.db_for_write(instance.__class__, instance=instance)
)


def instantiate_hooked_method(method: Any, callback_specs: HookConfig) -> AbstractHookedMethod:
Expand Down
6 changes: 6 additions & 0 deletions tests/db_router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class DBRouter:

def db_for_write(self, model, **hints):
if model._meta.app_label == "other":
return "post"
return None
7 changes: 7 additions & 0 deletions tests/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,16 @@
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
},
"other": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "other.sqlite3"),
}
}

DATABASE_ROUTERS = [
"tests.db_router.DBRouter"
]

# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
Expand Down
22 changes: 19 additions & 3 deletions tests/testapp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@ def do_after_create_jobs(self):
def timestamp_password_change(self):
self.password_updated_at = timezone.now()

@hook('before_update', when='first_name', has_changed=True)
@hook('before_update', when='last_name', has_changed=True)
@hook("before_update", when="first_name", has_changed=True)
@hook("before_update", when="last_name", has_changed=True)
def count_name_changes(self):
self.name_changes += 1

@hook("before_delete", when='has_trial', was='*', is_now=True)
@hook("before_delete", when="has_trial", was="*", is_now=True)
def ensure_trial_not_active(self):
raise CannotDeleteActiveTrial("Cannot delete trial user!")

Expand Down Expand Up @@ -148,3 +148,19 @@ def timestamp_created_at(self):
@hook("after_create")
def answer_to_the_ultimate_question_of_life(self):
self.answer = 42


# Model stored in other database
class Post(LifecycleModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
content = models.TextField(null=True)

@hook("after_create", on_commit=True)
def send_notification(self):
mail.send_mail(
"New Post!", "Click link below to have your latest post", "[email protected]", ["[email protected]"]
)


class Meta:
app_label = "post"
23 changes: 23 additions & 0 deletions tests/testapp/tests/test_post.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from django.core import mail
from django.test import TestCase

from django_capture_on_commit_callbacks import capture_on_commit_callbacks

from tests.testapp.models import Post

class PostTestCase(TestCase):
databases = ("default", "other",)

@property
def stub_data(self):
return {
"content": "plain text"
}

def test_send_notification_mail_after_create(self):
with capture_on_commit_callbacks(execute=True, using="other") as callbacks:
Post.objects.create(**self.stub_data)

self.assertEquals(len(callbacks), 1, msg=f"{callbacks}")
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, "New Post!")