I make a website on Django, Postgresql database

There are the following tables in the database:

  1. Faculty

    • Id
    • Title
  2. The Department

    • Id
    • Title
    • Faculty
  3. Teacher
    • Id
    • Name
    • The Department
  4. Book Editions
    • Teacher
    • Title
    • Publisher
    • The year of publishing

It is necessary to display this data on the page in a hierarchical form:

  1. Chemical faculty
    1. Department of Organic Chemistry
      • Sadulaev A.B.
        The book edition of this teacher
        The book edition of this teacher
      • Bogomoev A.P.
        The book edition of this teacher
        The book edition of this teacher
    2. Department of Biomolecular Chemistry
      • Boltukayev A.A.
        The book edition of this teacher
        The book edition of this teacher
        ...
      • Makhov B.V.
        ...
  2. Faculty of Mechanics and Mathematics
    1. Department of Applied Mathematics
      • Kolmogorov A.N.
        ...

What is the best way to do this?

I see while one option:

Get all the data in one sql query using inner-join
Faculty Department Teacher Edition
Chemical Biomolek. Boltukaev Edition
Chemical Biomolek. Boltukaev Edition
Chemical Biomolek. Makhov Edition
Math

Then process the result of this query in python and present it in a hierarchical form (a list of lists), making a bunch of cycles

  • And the question is what, since you already have a solution? - m9_psy
  • Is there a better way to do this? - AN
  • Read about the regroup template filter - if I understood you correctly, then this is what you need - Eduard Izmalkov
  • @ EdwardIzmalkov Thank you, regroup will also go. - AN

1 answer 1

This is a standard task for ORM, here ManyToOne links and greedy loading. https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_one/ http://djbook.ru/rel1.4/ref/models/querysets.html#prefetch-related

 data = Факультет.objects.all().prefetch_related('кафедры__преподаватели__издания') 

And displaying it all is easy in a loop.

 for факультет in data: for кафедра in факультет.кафедры: ... 

I do not know how the department and faculty correctly translate into English. In general, this is not a postgres task and do not join. In the current example there will be 4 queries of the type:

 select * from факультеты; select * from кафедры where id in (...id факультетов); select * from преподавалите where id in (...id кафедр); select * from книги where id in (...id преподов); 

Django all raspedalit himself inside.

  • Viewboy! What you need! Thank! - AN