2

I was looking for a field calculator plugin, but I think none exists.

I would like to have ideas or hints about the best way (simplest is the best) I could develop a plugin that allow user to make calculations on fields using mathematical expression.

For beginning I would just let user type an expression in a form and send it through ajax for instance:

'field4' = ('field1' + 'field2') / 'field3'

Then, I wonder how I could parse such expression (or any other similar) and do the calculation on the server side without bothering with validation for now.

import compiler

def fieldCalculator(request):
     queryset = Models.objects.all()

     eq = request.GET['expression']
     ast = compiler.parse(eq)

     #I wonder how to do this part using the parsed expression
     for object in queryset: 
       object.field4 = (object.field1 + object.field2) / object.field3
       object.save()

edit:

The expression would be user defined, so can take any number of fields and any mathematical operations (lets stay to the + - * / for now).

The expression in its generic way would be:

'output_field' = 'a mathematical expression using variables (other fields) and constants'
Below the Radar
  • 7,321
  • 11
  • 63
  • 142
  • An interesting idea, but I think you have to do a lot lifting for parsing and validation on user's input, don't you? – Jerry Meng Apr 23 '14 at 18:52
  • Would the structure of the expression be the same each time? i.e. would it always be field4 = (field1 + field2) / field 3, or could it be field4 = field1 X field2 - field3? The latter problem will be much more difficult. – Alex Apr 23 '14 at 18:54
  • yes thats right, validation is a step I can handle, but I bug on parsing the expression correctly – Below the Radar Apr 23 '14 at 18:54
  • @alex see edit on that – Below the Radar Apr 23 '14 at 18:55
  • 1
    I think you should start with looking for exist code for parsing mathematical expression. I bet there are some and it is hard for yourself to build one from scratch. – Jerry Meng Apr 23 '14 at 19:00
  • @Jerry Meng : yes definately, thanks for the suggestion – Below the Radar Apr 23 '14 at 19:02
  • 1
    Good point @JerryMeng. [Here's](http://stackoverflow.com/questions/594266/equation-parsing-in-python) a good answer from another Stack Overflow question and [here's](http://blog.erezsh.com/how-to-write-a-calculator-in-70-python-lines-by-writing-a-recursive-descent-parser/) a good blog post on writing your own Python calculator. – Alex Apr 23 '14 at 19:04

0 Answers0