My goal is to use d3js for a Django app to make a hierarchical tree of supervisors and employees. To do that, I understand that I need a hierarchy of JSON data (as seen in this example). My model contains data regarding employees and their supervisor:
class people(models.Model):
namelast = models.CharField(max_length=100, verbose_name='Last Name')
namefirst = models.CharField(max_length=100, verbose_name='First Name')
position = models.CharField(max_length=100)
supervisor = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Supervisor')
def __str__(self):
return "%s %s" % (self.namefirst, self.namelast)
A supervisor will have multiple "children," and those children may or may not be supervisors with more "children."
I've tried looping through the model objects, but haven't been able to come up with something hierarchical. The closest I've gotten is:
data = {}
for s in supervisors:
data['name'] = str(people.objects.get(pk=s))
children = people.objects.filter(supervisor=s)
cdict = {}
for c in children:
cdict.update({'name':str(c)})
data.update({'children':cdict})
But that isn't hierarchical, and the last line overwrites prior children because I'm running into the issue that Python dictionaries can't have multiple keys with the same name.
The output JSON I need is something like:
{
"name": "Bob",
"children": [
{
"name": "Mike"
},
{
"name": "Joe",
"children": [
{
"name": "Jane"
},
{
"name": "Chad"
}
]
}
]
}
Where Bob supervises Mike and Joe, and Joe supervises Jane and Chad. But with Python dicts, Joe's "children" can't both have the key name
.
Any advice on how I can prepare a Django model like this for use with d3js?