from django.db import models
from dataplot import GenericPlot
import pdb
# Start with models.Model
# examine all immediate subclasses using models.Model.__subclasses__()
# then examine each to see if it has a 'objects' attribute => data table
# if so, add to list of models we can plot with
# then examine its subclasses to see if we can find any more models
class subfinder(list):
"""Find all subclasses of m which are models with data.
"""
def __init__(self,C,required):
if required in dir(C):
T=(
'%s.%s'%(C.__module__,C.__name__),
'%s (%s)'%(C.__name__,C.__module__),
)
self.append(T)
for SC in C.__subclasses__():
self += subfinder(SC,required)
MODELS=subfinder(models.Model,'objects')
PLOT_TYPES=subfinder(GenericPlot,'get_kwargs')
class Dataplot(models.Model):
"""Plot of every instance in model.
"""
model=models.CharField(max_length=255,choices=MODELS)
type=models.CharField(max_length=255,choices=PLOT_TYPES)
model_doc=models.TextField(blank=True)
type_doc=models.TextField(blank=True)
class Admin:
list_display=(
'id','type','model'
)
fields=(
(None,{
'fields':('type','type_doc'),
}),
(None,{
'fields':('model','model_doc'),
}),
)
def get_plot_class(self):
"""Plot class defined by database values.
"""
return self.get_module_item('type')
def get_model(self):
return self.get_module_item('model')
def get_module_item(self,import_path):
L=getattr(self,import_path).split('.')
m=__import__('.'.join(L[:-1]),[],[],' ')
return getattr(m,L[-1])
def get_data(self):
pdb.set_trace()
for a in self.argument_set.all:
pass
def save(self):
C=self.get_plot_class()
self.type_doc=C.__doc__
M=self.get_model()
fields=[f.name for f in M._meta.fields]
self.model_doc='fields available for use as arguments: %s'%fields
super(Dataplot,self).save()
P=C('dataplot/dataplotid%s-%s-%s'%(self.id,self.model,self.type),
self.get_data)
kwargs=P.get_kwargs()
for k,v in kwargs.items():
A,C=Argument.objects.get_or_create(dataplot=self,key=k)
if C:
A.value=v
A.save()
def __unicode__(self):
return '%s(%s)'%(self.type,self.model)
class Argument(models.Model):
"""Named argument to pass to dataplot function.
"""
dataplot=models.ForeignKey(Dataplot)#,edit_inline=True)#NEED TO FIX ,num_in_admin=0)
key=models.CharField(max_length=255,null=False,default='')#,core=True)
value=models.CharField(
max_length=255,null=True,default='')#,core=True,blank=True)
def __unicode__(self):
return "%s=%s"%(self.key,self.value)
class Meta:
unique_together=(
('dataplot','key'),
)