I am working on importing XML data into Django models. For example, I could use the following XML:
<family surname="Jones">
<person name="Bob" />
</family>
to populate the following Django models:
class Family(models.Model):
surname = models.CharField(max_length=255)
class Person(models.Model):
family = models.ForeignKey(Family, related_name="people")
name = models.CharField(max_length=255)
In the XML, there is the concept of ‘triggers’ with ‘conditions’. For example:
<trigger>
<condition ... />
<action>Do something</action>
</trigger>
A trigger may have one condition-type element, where ‘condition-type’ means either a condition element or an element containing a group of condition elements (ie. and or or), which are to be read as ‘if all the conditions evaluate’ or ‘if some of the conditions evaluate’. Each ‘condition group’ may in turn contain one or more condition-type elements. A more complex example follows:
<trigger>
<and>
<condition />
<or>
<condition />
<condition />
<and>
<condition />
<condition />
</and>
</or>
</and>
<action>Do something</action>
</trigger>
I can’t figure out the best way to model this with Django. Ideally I’d like the Trigger model to link to an abstract ConditionType model (which can be either a Condition or a ConditionGroup), and the ConditionGroup model (but not the Condition model) to link to multiple ConditionType models.
I’m reasonably new to Django models. I have read the documentation with regards to model inheritance, but still can’t figure out how to model something quite so complex as this. Does anyone have any ideas?
So, I eventually solved the problem by having the following three classes:
ConditionGroup,SubConditionGroupandCondition.SubConditionGroupinherits fromConditionGroup.ConditionGroups may be of type ‘single’, ‘and’ or ‘or’, where ‘single’ contains aConditionand the other two can contain multipleSubConditionGroups.So, my finished model looks something like this: