Django:我如何为异构数据类型的树建模?

Cor*_*rey 5 database django database-design django-models django-treebeard

我需要在我的数据库中存储树数据结构,我计划使用django-treebeard或者django-mptt.我的混淆源是每个节点可能是三种不同的可能类型之一:根节点将始终是类型A实体,叶节点是类型C实体,其间的任何东西将是类型B实体.我想知道模拟这种情况的最佳方法.

更新: 我首先尝试了模型继承,我认为这可能是最好的方法.不幸的是,django-treebeard的公共API实际上并不是为处理这个而设计的.我最终得到它与GenericForeignKey一起工作.非常感谢您的回答.

Jon*_*nan 3

如何使用模型中的通用关系来保存树结构与其表示的节点的内容对象?

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Node(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    object = generic.GenericForeignKey('content_type', 'object_id')
Run Code Online (Sandbox Code Playgroud)

在检索完整树的内容对象时,这可能会导致大量查询,但是有一些方法和手段可以减少所需的查询数量。

# Assuming mptt, as I'm not familiar with treebeard's API

# 1 query to retrieve the tree
tree = list(Node.tree.all())

# 4 queries to retrieve and cache all ContentType, A, B and C instances, respectively
populate_content_object_caches(tree)
Run Code Online (Sandbox Code Playgroud)