Django:简单层次结构的最佳方法?
我有这个模型:
class Category(models.Model):
name = models.CharField()
description = models.CharField(blank=True)
parent = models.ForeignKey('self', blank=True, null=True)
我希望 Django 根据类别的层次结构对类别进行排序,例如:
- Parent 1
- 孩子 1
- 父 2
- 孩子 1
我做了一些研究,发现了 2 个应用程序,treebeard.al_tree 和 Django MPTT,这两个应用程序都很强大,但可能会导致性能较低或难以维护。
我将在网站的侧边栏和内部管理页面中显示类别(包括帖子模型中的ForeignKey),对类别的添加/修改/删除非常少,主要是只读,这对性能不会有太大影响。
有没有其他应用程序可以提供此功能并且比上述应用程序更简单? 我可以使用 Django 来实现此目的,而无需使用其他应用程序、管理器或其他东西吗?
I have this model:
class Category(models.Model):
name = models.CharField()
description = models.CharField(blank=True)
parent = models.ForeignKey('self', blank=True, null=True)
I want Django to sort the categories with respect to their hierarchy, for example:
- Parent 1
- Child 1
- Parent 2
- Child 1
I did some research and found 2 apps, treebeard.al_tree and Django MPTT, both are powerful which may lead to lower performance or harder to maintain.
I will display the categories in website's sidebar and inside admin pages (includes ForeignKey in posts model), there will be very low additions/modifications/deletions to categories, mostly reading only which should have no big affect on performance.
Is there any other app which offers this and simpler than those above?
Can I achieve this using Django without additional apps, using managers or something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我没有看到使用 django-mptt 这样的应用程序有任何缺点。事实上,它提供的方法经过优化,可以在执行具有层次结构的查询时为您提供最大的性能。我没有理由担心可维护性和/或性能,而且它非常容易使用!
I do not see any disadvantes using an app like django-mptt. In fact the methods provided by it are optimized to give you a maximum in performance when doing queries with hierarchical structures. No reason for me to worry about maintainability and/or performance and it is quite easy to use!
MPTT 或 Treebeard 可能会导致性能降低?废话。这些应用程序的重点在于它们提供了高度优化的算法,可以大幅提高性能。 MPTT 允许您通过单个数据库操作来获取整个树或其中的子部分,否则这将需要许多单独的调用。
MPTT or treebeard may lead to lower performance? Nonsense. The whole point of these apps is that they provide highly optimised algorithms that massively increase performance. MPTT allows you to grab whole trees or sub-sections of them with a single database operation, which would otherwise need many separate calls.
使用 MPTT 可以使系统正常运行。当您自己实现它时,您最终可能会手动将节点连接在一起(大约 30 行函数),或者对所有子级别进行单独查询。很多手工工作,都在那里完成了。
使用MPTT算法,可以在一次查询中获取一棵子树。
这是存储分层数据的常见算法。
Django MPTT(尤其是 v0.4)有一些很好的 API,可以在管理和模板中正确显示所有这些数据。您不必重新发明轮子。
Using MPTT is there to make the system perform. When you implement it yourself, you may end up connecting the nodes together manually (a ~30 line function), or doing individual queries for all sublevels. Lots of manual work, been there, done that.
With the MPTT algorithm, a subtree can be fetched in one query.
It's a common algorithm to store hierarchical data.
Django MPTT (especially v0.4) has some nice API's to display all this data properly in the admin and templates. You don't have to reinvent the wheel.