简体   繁体   中英

sqlalchemy: how to organize making new instances of classes?

I have a Flask application running sqlalachemy. I'm pretty new to sqlalchemy so I'm really confused. I've made a bunch of classes:

User Course Lecture Note Queue Asset

All of which have relationships- Users have many courses, courses have many users, users have many lectures, lectures have many users, users have many notes, notes have many users, courses have many lectures, lectures have many notes, courses have many notes, lecture has a 1 to 1 with queue, a user can have many queues and a queue needs many users, etc etc

So whenever I create a lecture, do I have to instantiate it in all the other things related to it as well?

For example, this is the code I've written for making a new lecture

def createLecture(user, course):
    # user and course are existing objects fetched from the db already
    # create new lecture
    newLecture = Lecture()
    db.session.add(newLecture)

    # add lecture to course, add new queue to lecture, add user to queue, add user to lecture
    course.lectures.append(newLecture)
    lecture.users.append(user)
    newQueue = Queue()
    db.session.add(newQueue)
    newQueue.users.append(user)
    newQueue.lecture = newLecture
    db.session.commit()

    return newLecture

This strikes me as ridiculously convoluted and confusing. On top of being confusing, I don't even know if I covered all of the relationships that I should be making (it's easy to forget one with so many).

There has to be some better way to add a new object when it's tied to many other objects with various relationships.

How can I be more organized?

Since this was a complex database schema, I double checked every relationship and made sure it was specified correctly.

In examining my schema, I figured that some relationships can be fulfilled when the object is instantiated , and that is the best way to reduce code messiness.

So my example from above is written as:

def createLecture(user, course):
# create new lecture
now = datetime.now()
dt = now.strftime("%Y-%m-%d-%H-%M")
newLecture = Lecture(dt, course)
db.session.add(newLecture)

# add lecture to course, add new queue to lecture, add user to queue, add new user to lecture
newQueue = Queue(newLecture)
db.session.add(newQueue)
newLecture.users.append(user)
newQueue.users.append(user)
newLecture.groupID = pad.createGroupIfNotExistsFor(newLecture.course.name+dt)['groupID']

db.session.commit()
return newLecture

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM