Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

python - Reference to other Documents as map or dict with int keys in mongoengine

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...