I'm setting up a Mongo database with mongoengine for course programs and courses. Courses have a certain level that depends on the program. For example course A may be level 1 in course programs A and C, but level 2 in course program B. I want to create bi-directional links between the courses and programs. This reference should also store the level of the course.
The idea is that I can easily query for a given course program what e.g. the level 1 courses are, or for a given course the programs for which it is in level 1.
With regular Python classes I might do it using dicts, as follows:
class CourseProgram():
pass
class Course():
pass
programA = CourseProgram()
programB = CourseProgram()
programC = CourseProgram()
courseA = Course()
courseA.programs = {programA : 1, programB : 2, programC : 1}
programA.courses = {courseA : 1}
programB.courses = {courseA : 2}
programC = {courseA : 1}
Alternatively, it could be structured as follows:
courseA.programs = {1: [programA, programC], 2: [programB]}
programA.courses = {1: [courseA]}
programB.courses = {2: [courseA]}
programC.courses = {1: [courseA]}
What's a logical way to design this in mongoengine? I considered both MapField
and DictField
for the fields but they require the keys to be strings. This rules out the first option. For the second option I could use str
instead of int
for the keys. However, I'm wondering if there's a better way to do this.
question from:
https://stackoverflow.com/questions/65885469/reference-to-other-documents-as-map-or-dict-with-int-keys-in-mongoengine 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…