Creating an unlimited forum hierarchy in Django

后端 未结 2 979
悲哀的现实
悲哀的现实 2021-01-16 04:31

I\'m trying to design models for a forum I wish to create in Django.

So far I have:

class Forum(models.Model):
    name = models.CharFie         


        
2条回答
  •  无人及你
    2021-01-16 04:37

    I would simply create one Forum model that can either have another Forum as it's parent, or have a null parent. Then if you want to print out all parents you could use a while loop like this pseudocode:

    heirarchy = ""
    f = this forum model
    while f.parent is not null:
       heirarchy.append(f.parent.name)
       f = f.parent
    

    to answer the other part of your question, in order to select a child while knowing the parent id, you would query Django's object structure like so:

    Forum.objects.filter(parent=PARENT_ID)
    

    and to get the grandparent of a child you would do:

    forum_object.parent.parent
    

提交回复
热议问题