Questo è uno schema di comando scritto per django 1.4
Può essere usato nel seguente modo:
p = DesignPattern()
imps = Implementation.objects.filter(project='Example')
DesignPatterImplementationsM2MBind(p, imps)
File model.py di applicazione Django:
class AbstractM2MBindCommand(AbstractCommand):
"""
Realizes behaviour design pattern 'Command'
"""
model = None
model_m2m_field = None
MAX_COMMA_SEPARATED_LENGTH = 1024
bound_objects = models.CommaSeparatedIntegerField(max_length=MAX_COMMA_SEPARATED_LENGTH, null=True, blank=True, default=None)
bound_objects_long = models.TextField(null=True, blank=True, default=None)
class Meta:
abstract = True
@classmethod
def do(cls, model_instance, queryset_to_link):
#assert isinstance(queryset_to_link, QuerySet)
setattr(model_instance, cls.model_m2m_field, queryset_to_link)
ids = [u'%d' % item.pk for item in queryset_to_link]
model_instance.save()
fk_field = camel_to_underscore_convert(cls.model.__name__)
cmd = cls()
cmd.direction = cls.FORWARD
joined_ids = u','.join(ids)
if len(joined_ids) > cls.MAX_COMMA_SEPARATED_LENGTH:
cmd.bound_objects_long = joined_ids
cmd.bound_objects = None
else:
cmd.bound_objects_long = None
cmd.bound_objects = u','.join(ids)
setattr(cmd, fk_field, model_instance)
cmd.save()
@classmethod
def undo(cls, command_id):
pass
@classmethod
def redo(cls, command_id):
pass
class DesignPatterImplementationsBindCommand(AbstractM2MBindCommand):
model = DesignPattern
model_m2m_field = 'implementations'
design_pattern = models.ForeignKey(DesignPattern)