How to store a boolean expression (parse tree) in a model?

54 views
Skip to first unread message

test

unread,
Feb 18, 2020, 6:13:39 PM2/18/20
to Django users
Let's say I have:

Calculator #1:
Expression: (True AND False) AND (True OR False)

This expression should be a child of some calculator. 

class Calculator(models.Model):
name = ...

class Expression(models.Model):
parent = models.ForeignKey(Calculator)

boolean = AND or OR

sub_exp1 = models.ForeignKey(Expression)
sub_exp2 = models.ForeignKey(Expression)


When I query all the expressions for the Calculator #1, I should get all the subexpressions.

1 AND 2 5
2 AND 3 4
3 leaf node of True 
4 lead node of False
5 OR 6 7
6 leaf node of True
7 leaf node of False

From this, I can quickly apply my parse tree.

How would I display the base case/leaf nodes in my model? Also, is there a better way?

Thanks, I would really appreciate any help

Simon Charette

unread,
Feb 18, 2020, 11:30:40 PM2/18/20
to Django users
I suggest you have a look at the "Trees and Graph" section of the
Django Packages website[0]. I've personally used MPTT and Treebeard
in the past without too much trouble.

You could also a field able to store composite data structures
such as JSONField or even a dedicated PostgreSQL type[1] to efficiently store
such data.

Cheers,
Simon

test

unread,
Feb 19, 2020, 12:15:32 PM2/19/20
to Django users
thanks, do you know how i can create custom leaf nodes when using MPTT or treebeard?

My parent nodes should have connector types such as AND/OR but the child should not

Simon Charette

unread,
Feb 19, 2020, 2:29:10 PM2/19/20
to Django users
Could you simply make the connector field nullable to express that?

Simon
Reply all
Reply to author
Forward
0 new messages