使用从保存树结构的模型到表示节点的内容对象的通用关系如何?
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)