0

I am experimenting a smart calculator (with some strange operating methods). It manipulates objects which share common methods of calculus. These objects being operands and various operators. Here I am trying with only one kind of operator : PolarBinaryOperator (could be « power » for example), but there will be many others.

PolarBinaryOperator links two operands. Operands don’t share attributes, only methods like calculation methods.

Inheritance :

  • I can’t make operand an abstract class because it needs to be linked by operators like the PolarBinaryOperator.
  • I can’t make all operands a unique model named operand with some null values, always the same giving the real nature of the operand. But giving the type of operator, the linked objects could be other operands or objects.
  • I have tried using content type for generic operator relations but it gives poor speed performance.
  • I have tried multi-table inheritance but it gives poor speed performance.

Am I stuck with the content type solution ? Or could there be another possible pattern ?

class Operand(models.Model):
    def _nexts(self):
        nexts = Operand.objects.filter(
            lien_operand_origin__operand_origin=self)
        return nexts

    def calculate(self):
        pass

    def calculate2(self):
        pass


class Integer(Operand):
    value = models.models.IntegerField()


class Operator(Operand):
    # Relations
    operand_origin = models.ForeignKey(
        'Operand', related_name='destination_operand')
    operand_destination = models.ForeignKey(
        'Operand', related_name='origin_operand')


class PolarBinaryOperator(Operator):
    type_operator = models.CharField(
        choices=NATURE_CHOICES,
        max_length=2,
    )
Proph73
  • 37
  • 1
  • 5
  • 1
    I know very little Django, but it I understand it and your question correctly, you are essentially looking for a way to represent an expression tree inside a relational database. That explains to non-Djangoists why typical Python idioms won't apply. I wonder whether questions such as [php / Mysql best tree structure](https://stackoverflow.com/q/5916482/1468366) will add any value over what you have. I'd try a single table with id, opcode, value (for leafs), lhs_id, rhs_id (both for bin ops). Which I think is your 2nd option, so I for one don't fully understand why that's not an option here. – MvG Sep 30 '18 at 20:16
  • Thank you, interesting designs and django-treebeard seems a library to implement it easily. Though for some applications, from an operand that would be found in several independent calculations, I would like to access each of these calculations. It is therefore not a tree structure but more like a graph structure. – Proph73 Sep 30 '18 at 21:40

0 Answers0