Skip to content
This repository has been archived by the owner on May 7, 2019. It is now read-only.

Commit

Permalink
Added depth attribute to hold the level of a node relative to its roo…
Browse files Browse the repository at this point in the history
…t node
  • Loading branch information
nylar committed May 19, 2015
1 parent c044388 commit 666a0e9
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
19 changes: 19 additions & 0 deletions posts/migrations/0002_post_depth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

dependencies = [
('posts', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='post',
name='depth',
field=models.PositiveSmallIntegerField(default=0),
),
]
6 changes: 6 additions & 0 deletions posts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class Post(models.Model):
slug = models.SlugField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
depth = models.PositiveSmallIntegerField(default=0)

# Foreign Keys
thread = models.ForeignKey('threads.Thread')
Expand All @@ -29,4 +30,9 @@ def __unicode__(self):
def generate_slug(sender, instance, created, **kwargs):
if created:
instance.slug = HASHER.encode(instance.pk)
# Calculate the depth for a comment, root nodes are 0 and those with
# children take their parent's depth value plus one.
depth = 0 if instance.parent is None else instance.parent.depth + 1
instance.depth = depth

instance.save()
7 changes: 7 additions & 0 deletions posts/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,10 @@ def test_thread_created_date_and_updated_date(self, mock_now):
message='Post', thread=self.thread, parent=None)
self.assertEqual(p.created, datetime.datetime(2015, 1, 1))
self.assertEqual(p.updated, datetime.datetime(2015, 1, 1))

def test_post_depth(self):
self.assertEqual(self.post.depth, 0)

p = Post.objects.create(
message='A Child', thread=self.thread, parent=self.post)
self.assertEqual(p.depth, 1)

0 comments on commit 666a0e9

Please sign in to comment.