数据库 – Django:如何为异构数据类型树建模?

前端之家收集整理的这篇文章主要介绍了数据库 – Django:如何为异构数据类型树建模?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在我的数据库中存储树数据结构,我计划使用 django-treebearddjango-mptt.我的混淆源是每个节点可能是三种不同的可能类型之一:根节点将始终是类型A实体,叶节点是C类实体,其间的任何东西都是B类实体.我想知道模拟这种情况的最佳方法.

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

解决方法

如何使用模型中的 generic relation将树结构保存到它所代表的节点的内容对象中?
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')

在检索完整树的内容对象时,这可能会导致大量查询,但是有减少所需查询数量ways and means.

# 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)
原文链接:https://www.f2er.com/mssql/83735.html

猜你在找的MsSQL相关文章