📜 ⬆️ ⬇️

Tree Objects in Jang

Working on one project, I was faced with the need to keep the company's divisions in the form of a tree structure. I implemented it like this:


simplified unit model:
class Department (models.Model):
name = models.CharField (maxlength = 255, null = False, blank = False)
code = models.CharField (maxlength = 15, unique = True, null = False, blank = False)
path = models.CharField (maxlength = 255, null = False, editable = False)
parent = models.ForeignKey ('self', null = True, blank = True)


those. the model refers to itself. The key word here is path: here we will store the “path” to the current model through all ancestors. To generate it automatically, override save:
')
def save (self):
if self.parent:
self.path = '% s% s /'% (self.parent.path, self.code)
else:
self.path = '/% s /'% self.code
super (type (self), self) .save ()
for a in Department.objects.filter (parent = self.id):
a.save ()


thus, when the object is saved, the path field is “regenerated” for all its descendants.

Now you can select, say, all the employees of a given and all the subdivisions invested in it by a simple query:

staff = Staff.objects.filter (department__path__startswith = department.path)


for the final beauty guidance, we define __str__ for the Department object:
def __str __ (self):
return "% s% s"% ('------' [: self.path.count ('/', 2) -1], self.name)


Now in all forms when choosing a unit, the degree of its nesting will be visible.

Source: https://habr.com/ru/post/5959/


All Articles