Django:如何建模一个异构数据类型的树? [英] Django: How do I model a tree of heterogeneous data types?

查看:164
本文介绍了Django:如何建模一个异构数据类型的树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to store a tree data structure in my database, for which I plan on using django-treebeard or possibly django-mptt. My source of confusion is that each node could be one of three different possible types: root nodes will always be a type A entity, leaf nodes a type C entity, and anything in between will be a type B entity. I would like to know the best way to model this situation.

更新:我第一次尝试模型继承,我认为这可能是最好的方式去。不幸的是,django-treebeard的公共API不是真正设计来处理这个。我最终得到它使用GenericForeignKey。非常感谢您的答案。

update: I first tried model inheritance, and I think that this could be the best way to go. Unfortunately django-treebeard's public API isn't really designed to handle this. I ended up getting it to work with GenericForeignKey. Thank you very much for the answers.

推荐答案

如何使用通用关系从模型中将树结构保存到它代表的节点的内容对象?

How about using a generic relation from the model which will hold the tree structure to the content object for the node it represents?

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')

这可能会导致大量查询内容对象,但有方法和手段减少所需的查询数量。

This could potentially result in a lot of queries when retrieving content objects for the full tree, but there are ways and means of reducing the number of queries required.

# 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)

这篇关于Django:如何建模一个异构数据类型的树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆