Ordered lists in django

发布于 2021-01-29 16:00:03

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?

关注者
0
被浏览
44
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    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 !



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看