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

查看:26
本文介绍了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天全站免登陆