Skip to content

pinoatrome/django-strategy-field

 
 

Repository files navigation

django-strategy-field

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 links

Stable master-build master-cov  
Development dev-build dev-cov  
Project home page: https://github.com/saxix/django-strategy-field
Issue tracker: https://github.com/saxix/django-strategy-field/issues?sort
Download: http://pypi.python.org/pypi/django-strategy-field/

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python 98.5%
  • Makefile 1.5%