5๐
My thought is that if I could just reference this different algorithms
on a Model Field
This is a good idea, for example:
CALCULATION_TYPES = [(1, 'Normal'), (2, 'Express')]
class FreightTable(models.Model):
# Normal fields
calculation_type = models.IntegerField(choices=CALCULATION_TYPES)
def calc_normal(self):
pass
def calc_express(self):
pass
def calc_default(self):
pass
Now, for each freight type, you set your calculation method:
ft = FreightType(calculation_type=2)
ft.save()
At the point where you want to display the result of the calculation, fetch the method from the instance, and then call the appropriate method:
call_map = {1: 'calc_normal', 2: 'calc_express'}
ft = FreightTable.objects.get(pk=1)
calculated_value = getattr(ft, call_map(ft.calculation_type))()
2๐
Python classes, functions and methods cannot be pickled, so you cannot store the code itself in the database.
What you can do is
1) Store the full dotted path to the function in a CharField. Then resolve the reference to function using zope.dottedname package, and call it.
or
2) Store the calculation code as Python source code in the database as plain text. Then execute it through eval()
or dynamic module import using imp
module
I am not sure if Django had internal dotted name resolver, you could use it instead of zope.dottedname.
- [Django]-Automatically import all db tables in manage.py shell
- [Django]-Is there a simple way to create Chained Dynamic Drop Down List in Django Admin Site?