我正在使用Flask和SQLAlchemy以及我的数据库中的多对多关系。它工作正常,但我想在我的表user_routes
中添加新属性(String tarif)。如何在查询中编辑此属性?有可能的?谢谢
这是我要插入的数据库查询
route = get_route(request.form['fromStation'],request.form['toStation'],date_object)
user = get_user(request.form['userToken'])
route.users.append(user)
user.routes.append(route)
db.session.commit()
from app import db
user_routes = db.Table('user_routes',
db.Column('route_id', db.Integer, db.ForeignKey('route.route_id'), primary_key=True),
db.Column('user_id', db.Integer, db.ForeignKey('user.user_id'), primary_key=True)
)
class User(db.Model):
user_id = db.Column(db.Integer, primary_key=True)
token = db.Column(db.String(255), unique=True)
routes = db.relationship("Route", secondary=user_routes)
def __repr__(self):
return '<User %r>' % (self.token)
class Route(db.Model):
route_id = db.Column(db.Integer, primary_key=True)
route_from = db.Column(db.String(100))
route_to = db.Column(db.String(100))
date_time = db.Column(db.DateTime)
free_seats = db.Column(db.Integer)
users = db.relationship("User", secondary=user_routes)
def __repr__(self):
return '<Route %r>' % (self.route_id)
答案 0 :(得分:4)
下班后。我找到了解决方案Association Object
。
from app import db
class User_has_route(db.Model):
__tablename__ = 'user_has_route'
route_id = db.Column(db.Integer, db.ForeignKey('route.route_id'), primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), primary_key=True)
tarif = db.Column(db.String(30))
route = db.relationship("Route", back_populates="users")
user = db.relationship("User", back_populates="routes")
class User(db.Model):
__tablename__ = 'user'
user_id = db.Column(db.Integer, primary_key=True)
token = db.Column(db.String(255), unique=True)
routes = db.relationship("User_has_route", back_populates="user")
def __repr__(self):
return '<Userik %r>' % (self.token)
class Route(db.Model):
__tablename__ = 'route'
route_id = db.Column(db.Integer, primary_key=True)
route_from = db.Column(db.String(100))
route_to = db.Column(db.String(100))
date_time = db.Column(db.DateTime)
free_seats = db.Column(db.Integer)
users = db.relationship("User_has_route", back_populates="route")
def __repr__(self):
return '<Route %r>' % (self.date_time)