我正在尝试在Flask-SQLAlchemy中创建多对多关系,但似乎不知道如何填写多对多标识数据库(many to many identifier database)。您能帮我理解我错在哪里以及应该如何实现吗?
class User(db.Model):
__tablename__ = 'users'
user_id = db.Column(db.Integer, primary_key=True)
user_fistName = db.Column(db.String(64))
user_lastName = db.Column(db.String(64))
user_email = db.Column(db.String(128), unique=True)
class Class(db.Model):
__tablename__ = 'classes'
class_id = db.Column(db.Integer, primary_key=True)
class_name = db.Column(db.String(128), unique=True)
然后是我的标识符数据库:
student_identifier = db.Table('student_identifier',
db.Column('class_id', db.Integer, db.ForeignKey('classes.class_id')),
db.Column('user_id', db.Integer, db.ForeignKey('users.user_id'))
)
目前当我尝试将数据插入到数据库时,它看起来是这样的。
# User
user1 = User(
user_fistName='John',
user_lastName='Doe',
user_email='john@doe.es')
user2 = User(
user_fistName='Jack',
user_lastName='Doe',
user_email='jack@doe.es')
user3 = User(
user_fistName='Jane',
user_lastName='Doe',
user_email='jane@doe.es')
db.session.add_all([user1, user2, user3])
db.session.commit()
# Class
cl1 = Class(class_name='0A')
cl2 = Class(class_name='0B')
cl3 = Class(class_name='0C')
cl4 = Class(class_name='Math')
cl5 = Class(class_name='Spanish')
db.session.add_all([cl1, cl2, cl3, cl4, cl5])
db.session.commit()
我的问题是如何向多对多数据库添加内容, 因为我真的不能创建一个 'student_identifier' 对象?如果我可以的话,它可能会看起来像这样:
# Student Identifier
sti1 = StiClass(class_id=cl1.class_id, class_name=user1.user_id)
sti2 = StiClass(class_id=cl3.class_id, class_name=user1.user_id)
sti3 = StiClass(class_id=cl4.class_id, class_name=user1.user_id)
sti4 = StiClass(class_id=cl2.class_id, class_name=user2.user_id)
db.session.add_all([sti1, sti2, sti3, sti4])
db.session.commit()
我应该如何使用ORM插入多对多表?
students = db.relationship("Student", secondary=student_identifier, lazy='subquery', backref=db.backref('classes', lazy=True))
- Andrii Danyleikosession.execute( student_identifier.insert(), params={"class_id": class_id, "user_id": user_id}, )
- Edword