Any suggestion on how to decorate a model with extra attributes?

On Jan 1, 9:39 am, sagi s <sag...@yahoo.com> wrote:
> I'd like to store extra attributes in the model fields so I can
> control the subsequent field-specific behavior from there.
>
> Let's say I have a model that stores metrics I then need to chart.
>
> In the view, I prefer not to have some logic that says:
>
> metrics = Metric.object.all()
> create_chart([metric.productivity for metric in metrics], "bar_chart")
> create_chart([metric.defects for metric in metrics], "pie_chart")
>
> I'd rather have something like:
>
> for metric_type in Metric.fields:
>   create_chart([metric."metric_type" for metric in metrics],
> metric."metric_type".chart_type)
>
> The big advantage here is that I can add a new metrics element from
> the model without changing the view (Open-Close principle...)
>
> So it would be great if I could do  something like:
>
> class Metric(models.Model):
>   productivity = PositiveIntegerField(
>     verbose_name = "the number of hot dogs we have produced during
> that period",
>     chart_type = "bar_chart"
>    )
>   ...
>
> However the model rejects fields it does not recognize.
>
> I tried creating my own doctored model to wrap the built-in models:
>
> class _PositiveIntegerField(models.fields.CharField):
>     def __init__(self, *args, **kwargs):
>         if "extra_attrs" in kwargs:
>             self.extra_attrs = kwargs["extra_attrs"]
>             del kwargs["extra_attrs"]
>         models.fields.PositiveIntegerField.__init__(self, *args,
> **kwargs)
>
> This way I can do:
>
> class Metric(models.Model):
>   productivity = _PositiveIntegerField(
>     verbose_name = "the number of hot dogs we have produced during
> that period",
>     extra_attrs = {'chart_type' : "bar_chart"}
>    )
>   ...
>
> There are two problems here:
> 1. I'd need to wrap every field type
> 2. In the ModelForm I create from this model the type still registers
> as the built-in type:
>
> class MetricForm(models.ModelForm):
>   class Meta:
>     model = Metric
>
> >>> mf = MetricForm()
> >>> mf.fields['productivity']
>
> <django.forms.fields.PositiveIntegerField object at 0x12312312>
>
> Any suggestion as to how to design this right?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to