django中的有序列表 [英] Ordered lists in django

查看:98
本文介绍了django中的有序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很简单的问题。我需要创建代表有序列表元素的模型。这个模型可以这样实现:

  class Item(models.Model):
data = models.TextField )
order = models.IntegerField()

或像这样:

  class Item(models.Model):
data = models.TextField()
next = models.ForeignKey('self ')

什么方式是首选?每个解决方案有哪些缺点?

解决方案

本质上,您提出的第二个解决方案是一个链表。在数据库级别实现的链接列表通常不是一个好主意。要检索 n 元素的列表,您将需要 n 数据库访问(或使用复杂的查询)。性能明智,在O(n)中检索列表是非常有效的。



在常规代码中,链表用于与阵列相比获得更好的插入性能(不需要移动所有元素)。在您的数据库中,只有2个查询更新所有元素并不复杂:

 更新item.order = item.order + 1 FROM item WHERE order> 3 
INSERT INTO项目(订单,...)VALUES(3,...)



<我记得看到一个可重复使用的应用程序,实现了所有这些和一个很好的管理界面,但我现在找不到...



总而言之,明确使用解决方案# 1,远离解决方案#2,除非你有非常好的理由不要!


i have very simple problem. I need to create model, that represent element of ordered list. This model can be implemented like this:

class Item(models.Model):
    data = models.TextField()
    order = models.IntegerField()

or like this:

class Item(models.Model):
    data = models.TextField()
    next = models.ForeignKey('self')

What way is preferred? What drawbacks have each solution?

解决方案

Essentially, the second solution you propose is a linked list. Linked list implemented at the database level are usually not a good idea. To retrieve a list of n elements, you will need n database access (or use complicated queries). Performance wise, retrieving a list in O(n) is awfully not efficient.

In regular code, linked list are used to get better insert performance compared to arrays (no need to move all elements around). In your database, updating all elements is not that complicated in only 2 queries :

UPDATE item.order = item.order + 1 FROM item WHERE order > 3
INSERT INTO item (order, ...) VALUES (3, ...)

I remember seeing a reuseable app that implemented all that and a nice admin interface, but I cant find it right now ...

To summarize, definitly use solution #1 and stay away from solution #2 unless you have a very very good reason not to !

这篇关于django中的有序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆