Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6348393
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T21:24:40+00:00 2026-05-24T21:24:40+00:00

I need to order a list of comments so they appear in their threaded

  • 0

I need to order a list of comments so they appear in their threaded order.

Each comment has a:

  • Top parent comment (for queries)
  • Parent comment
  • Indentation level

If I’m fetching the comments as a list, what would be the most efficient way of sorting it so each comment is below its parent?

It has to remain as a 1-dimensional list. I just want to rearrange the items. I’m trying this but it doesn’t work as the list is mutated during enumaration, breaking the counter:

i = 0;
for child in childList:
    ii = 0;
    for ch in childList:
        if (ch.reply == child.id):
            childList.insert(i+1, childList.pop(ii))

    ii += 1;
    i += 1;
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T21:24:41+00:00Added an answer on May 24, 2026 at 9:24 pm

    So… you’ve got something like this?

    class Comment(object):
        all_comments = []
    
        def __init__(self, message, parent):
            self.message = message
            self.parent = parent
            self.all_comments.append(self)
    
        def __iter__(self):
            """
            Yields tuples of (indentation level, comments), with this comment first
            and child comments later.
            """
            # what goes here?
    

    This just a depth-first pre-order tree traversal.

    import itertools
    
    class Comment(object):
        def __iter__(self):
            return _iter_helper(self, 0)
    
        def _iter_helper(self, depth):
            item = {'indent_level': depth, 'comment': self}
            return itertools.chain([item], 
                                   *[comment._iter_helper(depth+1)
                                     for comment 
                                     in self.all_comments
                                     if comment.parent == self])
    

    As Harypyon suggests, storing the children is a more efficient way of viewing this problem than storing the parent and then computing the children.

    EDIT:

    I don’t think storing children is possible with MySQL.

    Ok.. this is in a database and you (probably) want some SQL that produces the desired result?

    You’ve got a table like something like this?

    CREATE TABLE comments (
        id INTEGER PRIMARY KEY,
        parent INTEGER,
        comment TEXT        
    );
    

    Unfortunately, MySQL doesn’t support recursive query syntac (neither the with recursive common table expressions nor connect by), so this self referential schema, though simple and elegant, is not useful if you want to do the whole thing in a single query with arbitrary depth and all of the needed metadata.

    There are two solutions. First, you can emulate the recursive query by doing the equivalent of a common table query in python, or in MySQL using temporary tables, with each of the sub-selects as a separate actual query. The downside is that this is neither elegant (many sql queries) and wasteful, (extra data transmitted over the connection or stored on disk).

    Another option is to is accept that the transitive closure of the tree of comments is simply not computable, but that you can still make do with a compromise. You most likely don’t want (or need) to show more than a hundred comments at a time, and you similarly don’t need to show a depth of more than, say, 5 levels of nesting. To get more information, you would Just run the same query with a different root comment. Thus, you end up with a query something like

    SELECT c1.*, c2.*, c3.*, c4.*, c5.*
    FROM comments c1
    LEFT JOIN comments c2 ON c1.id = c2.parent
    LEFT JOIN comments c3 ON c2.id = c3.parent
    LEFT JOIN comments c4 ON c3.id = c4.parent
    LEFT JOIN comments c5 ON c4.id = c5.parent
    WHERE c1.parent = ?
    

    Which will give you a good “batch” of comments, up to 5 levels deep.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to sort list of strings in the alphabetical order: List<String> list =
I need a jQuery to order a list like this: http://jqueryui.com/demos/sortable/ But I need
I need to return an a generic list in the correct order for my
Let me explain: I need to sort a list in ascending order, while results
I need to generate a list of activity from multiple tables in order of
I need to get a list of Articles sorted by the latest Comment from
I have a problem with LINQ (in C#). I need to order a list
Essentially I need a count of each Entries Comments: SELECT e.*, COUNT(c.id) as comments
I am developping a site where users can post comments and each comment is
I need to order by 2 columns using the entity framework. How is that

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.