Skip to content

Instantly share code, notes, and snippets.

@az7arul
Created June 17, 2013 13:03
Show Gist options
  • Save az7arul/5796700 to your computer and use it in GitHub Desktop.
Save az7arul/5796700 to your computer and use it in GitHub Desktop.
Generating a hash for module inheritance
from django.db import models
class Module(models.Model):
title = models.CharField(max_length=200, blank=True, null=True)
description = models.CharField(max_length=400, blank=True, null=True)
parent = models.ForeignKey('self', blank=True, null=True)
def _get_attributes(self):
query = """SELECT T2.*, T1.lvl
FROM (
SELECT
@r AS _id,
(SELECT @r := parent_id FROM modules_module WHERE id = _id) AS parent_id,
@l := @l + 1 AS lvl
FROM
(SELECT @r := %s, @l := 0) vars,
modules_module m
WHERE @r <> 0) T1
JOIN modules_module T2
ON T1._id = T2.id
ORDER BY T1.lvl ASC;""" % self.id
for m in Module.objects.raw(query):
md = m.__dict__
remove_empty_keys(md)
yield md
def get_attributes(self):
return reduce(lambda f, i: dict(i.items() + f.items()), self._get_attributes())
def remove_empty_keys(d):
for key in d.keys():
if d[key] is None:
del d[key]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment