我正在尝试创建一个决策树结构,其中包含一个节点产生的多个类,但我不知道使用 Django 执行此操作的最佳方法是什么。
为了说清楚,这就是我想要做的(左子是条件有效时的情况,右子是条件无效时的情况):
(Condition A)
|
-------------------------------
| |
(Condition B) (Condition C)
| |
------------------ |------------
| | | |
(Cond D) <Category> + <Group> <Cat>+<Gr> (Cond D)
| |
.. ...
这个想法是将一对( <Category>
、 <Group>
)或另一个 <Node>
关联起来。作为一个儿子。问题是,“如何在 Django 中表示多个类字段?”
这是我的模型:
class GroupDecision(models.Model):
name = models.CharField(max_length=100)
# Other fields that may come later
class DecisionTree(models.Model):
name = models.CharField(max_length=100)
start_node = models.ForeignKey('Node')
# Other fields that may come later
class Node(models.Model):
name = models.CharField(max_length=100)
predecessor = models.ForeignKey('Node', null = True, blank = True, default = None)
successor = models.ForeignKey('SuccessorAssociation')
operation = models.ForeignKey('Filter')
class SuccessorAssociation(models.Model):
TARGET = (('C','Category'),('G','Group'),('N','Node'))
condition = models.BooleanField()
target_class = models.CharField(max_length=10,choices=TARGET)
target_pk = models.IntegerField()
我设法用SuccessorAssociation
“破解”它谁可以定位 <Category>
, <Group>
或<Node>
但我不喜欢这个实现,因为它不保留递归删除原则而不覆盖 delete()
方法。
最重要的是,我重写了 Django 本身管理的一些机制。
自定义字段是解决此问题的一种方法,但我不太熟悉它,我认为这是一种不成比例的方法。
有人可以帮我实现这个吗?
谢谢
最佳答案
使用contenttypes
框架和通用外键:https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations
关于python - 具有多个类关联作为后继的树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23886492/