Models question

Hi.

I am planning an app for schools and I am thinking about how the models and fields will be structured. I hope you will help me.

I am planning the following models and my question will be about how “deeply nested” the foreign key relationships can go logically.

I am planning on the following models:
Student (being in a…)
SchoolClass (being in a…)
Team (being in a…)
Departmening (being in a…)
School

All the models will have a name field, plus “more fields”.

So my questions are:
How will a “all students in a school” query look?
Is this “multiple nesting” best practice or is there a better way.
I wanted to name SchoolClass just Class (my native language word for it) but I wanted to avoid naming collision. What would a good way to name SchoolClass?

Hope you will give me your thoughts on this planning of the app.

They can go as deep as you need them to.

If you have the ForeignKeys defined as having the same name as the target class, and you have an instance of School named school, then the query for all Student in that school would be Student.objects.filter(schoolclass__team__departmening__school=school)

This is a “best practice”, but not the only viable option. There are other ways, but whether or not they’re “better” is both subjective and dependant upon the operational characteristics of the data. (These characteristics to consider include the sizes of the individual levels, the frequency of updates to the data, what the distribution of those updates are among different insert, updates, and deletions of each of the levels, and what the common operations are - what the common queries are expected to be relative to the uncommon queries - and what the relative number of queries are going to be performed to the number of updates.)

Another option to consider would be one of the hierarchical representations for this data. This structure is a hierarchy, with the characteristic of the number of levels being fixed and given. (See Some modelling advice - #12 by KenWhitesell for more thoughts on this.) If I were to make a guess as to some of the answers above, I could see where either a Nested Set Tree or a Materialized Path Tree could be quite useful for this.

Thank you for your answer. It really helps! :muscle:
I mispelled department, but I will leave it so it is linked to your reply.

You answered my in an other thread on model managers. Maybe I combine these two in a students.in_school.all() somehow.

These python structures are above my skill level I think, but I will read it with great interest.

Side note: The beauty of using something like the Treebeard library is that you don’t need to worry about implementing them.

But I still have to figure out how, why and when to use it :grin: