如何使用模型中的通用关系将树结构保存到它所代表的节点的内容对象?
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')
在检索完整树的内容对象时,这可能会导致大量查询,但有一些方法和方法可以减少所需查询的数量。
# 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)