tags:

views:

27

answers:

1

I am playing around with django and python and have hit a bit of a roadblock here. I query my model and return the objects and then perform some simple operations on the results and return them to the view. After the 2nd request the childs for the forum category are duplicated and I have no idea why this happens.

ForumBuilder class which builds a list of categories and appends forums for that category

class ForumBuilder:
    def childern(self, parent, forums):
        for forum in forums:
            if forum.parent is None or parent.id != forum.parent.id:
                continue
            parent.childs.append(forum)
    def build(self, forums):
        categories = []
        for forum in forums:
            if forum.parent is None:
                categories.append(forum)
            self.childern(forum, forums)
        return categories

The index view

def index(request):
    forums = Forum.objects.all().order_by('-order')
    builder = ForumBuilder()
    return render_to_response('forums/index.html', {'categories': builder.build(forums)})
+3  A: 

Let me guess... You have something like:

class Foo(object):
    childs = []

When you should have something like:

class Foo(object)
    def __init__(self):
        self.childs = []

The difference is that in the first case, all your Foo instance will share the same childs object (class attribute) and in the former each instance will have its own childs (instance attribute).

Paulo Scardine