Skip to main content

Django custom field to implement the strategy pattern

Project description

Set of custom fields useful to implement the Strategy Pattern with Django models.

The Strategies are displayed in SelectBoxes as standard choice field

This package provides the following custom fields:

  • StrategyField

  • MultipleStrategyField

  • StrategyClassField

  • MultipleStrategyClassField

The StrategyField can be accessed as instance of the model with an attribute context that points to model that ‘owns’ the field (inverse relation). So:

Example

from strategy_field.fields import StrategyField
from django.core.mail.backends.filebased.EmailBackend


class Event(models.Model):
    backend = StrategyField()

Event(sender='django.core.mail.backends.filebased.EmailBackend')

Use case

As example we can imagine an application that manages Events that need to be notified to users. Each Occurrence of Event can be notified using different transport, (email, sms,…). We want to be able to add/change the way we send notification, per event basis, simply using the Django admin panel.

from strategy_field.fields import StrategyField

from strategy_field.registry import Registry
from strategy_field.fields import StrategyField

class TransportRegistry(Registry)
    pass

class AbstractStrategy(object):
    def __init__(self, context):
        self.context = context

    def send(self):
        raise NotImplementedError

class EmailStrategy(AbstractTransport):
    def send(self):
        ...

class SMSStrategy(AbstractTransport):
    def send(self):
        ...
registry = TransportRegistry()
registry.register(EmailStrategy)
registry.register(SMSStrategy)

class Event(models.Model):
    sender = StrategyField(registry)

Event.objects.get_or_create(sender=EmailStrategy)
...
...
e = Event.objects.get(sender=EmailStrategy)
e.sender.send() # e.sender.context == e

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-strategy-field-0.3.tar.gz (15.0 kB view details)

Uploaded Source

File details

Details for the file django-strategy-field-0.3.tar.gz.

File metadata

File hashes

Hashes for django-strategy-field-0.3.tar.gz
Algorithm Hash digest
SHA256 4c84b6f7cf921febf555c08be462097fae220a08d279be7804e2c19d57bf74ab
MD5 bc1012476b1d9ffcbe16b5c89ebd8dac
BLAKE2b-256 7f18441b99f88f7b5bf4478af9b8286e44c1da294aab938bb2ee9248be824f45

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page