Reputation: 2817
A few days back I was messing around with Django, trying to get a feel for how stuff works, when I decided to try and build a simple forum, one that resembled a forum that I frequented (but is now closed down). The idea was that each of the comments would be parent to any number of comments, like so:
comment <--top
comment <-- comment "A"
comment <-- comment "B"
comment <-- comment "C"
comment <--C-1, reply to comment "C"
comment <-- C-1-1, reply to comment "C-1"
comment
comment
comment
comment <-- C-1-1-1 reply to C-1-1
comment
comment
comment
comment
comment
comment
comment
comment
comment
comment
comment
comment
The idea here is that replies to a comment would stuffed one level beneath it, and each comment, with the exception of the very first comment, has a parent. The thing is, although I get the idea behind implementing tree traversals, none of the books/articles I've read on the subject take Django into account (or the MVC pattern for that matter), so my question is how would I go about implementing this system in Django? (here's the model code i've got for reference :-/)
class Comment(models.Model):
Parent = models.OneToOneField('self', null=True)
Children = models.ForeignKey('self', null=True)
Author = models.ForeignKey(User)
Author_IP = models.IPAddressField()
Created_On = models.DateTimeField(auto_now_add=True)
Modified_On = models.DateTimeField(auto_now=True)
Body = models.TextField()
Upvotes: 0
Views: 1845
Reputation: 31828
Have a look at django-threadedcomments. It's purpose is more fit to be used as comments on a blog than a full featured forum, but if it doesn't fit your case, you can at least look at the source code and learn a couple things from it.
As far as tree-based structures go, there are three projects I'm aware of for Django's ORM: django-mptt (this one has the biggest "market share" with 3rd party django apps AFAIK), django-treebeard, and easytree (which is based on treebeard). Easytree comes with a nice admin interface, but the other two projects have at least patches in their issue trackers to add an admin interface (not sure if they integrated those patches already).
Upvotes: 2
Reputation: 6318
I would only define the parent and give it a related name
class Comment(models.Model):
parent=models.ForeignKey('self', related_name="children", null=True, blank=True)
#other fields
Then you could get its children
comment=Comment.objects.get(id=1)
children=comment.children.all()
for child in children:
morechildren=child.children.all()
Upvotes: 1