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

Add post_save and post_delete signals #96

Open
calitidexvii opened this issue Sep 4, 2020 · 1 comment
Open

Add post_save and post_delete signals #96

calitidexvii opened this issue Sep 4, 2020 · 1 comment
Labels
enhancement New feature or request

Comments

@calitidexvii
Copy link

Is your feature request related to a problem? Please describe.
It's a common feature to automatically update an index when saving or deleting an object. An easy way to abstract this behavior is using Django signals.

Describe the solution you'd like
For my own purposes, I've sub-classed AppSearchModel to add this behavior. This could be added directly to AppSearchModel in a future release, optionally with a setting to control whether or not to add the signals. Please note that Python's __init_subclass__ is supported in the app's targeted support versions (Python >= 3.6 and Django >= 2.2).

from django.db.models.signals import post_save, post_delete
from django.apps import apps
from django_elastic_appsearch.orm import AppSearchModel


class CustomAppSearchModel(AppSearchModel):
    class Meta:
        abstract = True

    @classmethod
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        # If indexing enabled
        if apps.get_app_config('django_elastic_appsearch').enabled:
            post_save.connect(cls.__post_save_receiver, sender=cls)
            post_delete.connect(cls.__post_delete_receiver, sender=cls)

    @staticmethod
    def __post_save_receiver(sender, instance, **kwargs):
        """Signal handler for when a sub-classed model has been saved."""
        instance.index_to_appsearch()

    @staticmethod
    def __post_delete_receiver(sender, instance, **kwargs):
        """Signal handler for when a sub-classed model has been deleted."""
        instance.delete_from_appsearch()
@CorrosiveKid
Copy link
Contributor

@calitidexvii Thanks for this, it's a good idea, do you want to share your solution as a pull request?

@CorrosiveKid CorrosiveKid added the enhancement New feature or request label Sep 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants