There is a model of units

class Subdivision(models.Model): name = models.CharField('Наименование', max_length = 200) parent = models.ForeignKey('self', null=True, blank=True) 

The data is output using the query subdivision = Subdivision.objects.all() , in an unsorted form. For example, there is data in the database:

  + ---- + ------------------------ + -------- +
 |  id |  name |  parent |
 + ---- + ------------------------ + -------- +
 |  1 |  Management |  null |
 |  2 |  Production Department |  1 |
 |  3 |  Accounting |  1 |
 |  4 |  Production workshop |  2 |
 + ---- + ------------------------ + -------- + 

All this is displayed as:

  1. Control
  2. Production Department
  3. Accounting
  4. Manufacturing facility

And you need to (keeping the hierarchy):

  1. Control
  2. Production Department
  3. Manufacturing facility
  4. Accounting

Those. the first is the subdivision with the parent field zero, then the subdivisions, then the subsidiary subdivisions of the subsidiary, and so on Is it possible to implement this sorting with django?

  • I think it makes no sense to implement this with django, the desired tree is easily built by hand with an ordinary python - andreymal

2 answers 2

You can, of course: subdivision = Subdivision.objects.all().order_by('parent')

order_by - sorts by the specified field. If you put a minus in the beginning .order_by('-parent') , it will sort in the reverse order.

  • This option does not suit me. As it was, there remains no hierarchy. - zakiroof

I decided this way, added the order field to the model. When saving, I add there something like a path.

 @receiver(pre_save, sender=Subdivision) def pre_save_subdivision(sender, instance, **kwargs): if(instance.parent==None): instance.order='1' else: old = sender.objects.all().order_by('-id')[0].id instance.order = instance.parent.order + '.' + str(old+1) 

Next, sort Subdivision.objects.all().order_by('order') . Eventually:

 + ---- + ------------------------ + -------- + ------- +
 |  id |  name |  parent |  order |
 + ---- + ------------------------ + -------- + ------- +
 |  1 |  Management |  null |  1 |
 |  2 |  Production Department |  1 |  1.2 |
 |  3 |  Accounting |  1 |  1.3 |
 |  4 |  Production workshop |  2 |  1.2.4 |
 + ---- + ------------------------ + -------- + ------- +

And it is displayed as I need:

  1. Control
  2. Production Department
  3. Manufacturing facility
  4. Accounting