考虑这个(django)模型:
class Source(models.Model):
# Some other fields
type = models.ForeignKey('Type')
class Type(models.Model):
# Some other fields
parent = models.ForeignKey('self')
该模型自身有一个外键,从而创建了一个层次结构。
假设我们有以下层次结构:
Website
Blog
News
Social Network
Q&A
Forum
Radio
Government radio
Pirate radio
Commercial radio
Internet radio
我如何有效地查询,以便如果我选择Source
by Type
,我也检索Sources
其中有一个Type
那是给定类型的孩子吗?
我尝试过遍历整棵树,但这显然不是很有效。
另一种选择是使用 ManyToManyField 并通过覆盖 save() 方法自动附加父类型。例如,如果选择“博客”,则还会创建“网站”记录。但这对我来说似乎太过分了。
django-mptt 或 django-treebeard 是分层数据的好帮手。它们都向您的模型添加额外的元数据以允许高效的查询。
如果您选择使用 django-treebeard 您的模型可能如下所示:
from django.db import models
from treebeard.mp_tree import MP_Node
class Source(models.Model):
# Some other fields
type = models.ForeignKey('Type')
class Type(MP_Node):
# Some other fields
name = models.CharField(max_length=100)
# parent gets added automatically by treebeard
# parent = models.ForeignKey('self', blank=True, null=True)
可以这样查询:
# get all Sources of Type type and descendants of type
type = Type.objects.get(name='Radio')
Source.objects.filter(type__in=type.get_descendants())
see https://django-treebeard.readthedocs.io/en/latest/api.html https://django-treebeard.readthedocs.io/en/latest/api.html更多可能的查询
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)