在SQLAlchemy中创建多对多关系

时间:2019-04-25 13:10:16

标签: python sqlalchemy flask-sqlalchemy

我有以下三种模型:

users_projects = db.Table('users_projects',
    db.Column('user_id', db.Integer,
              db.ForeignKey('user.id'), primary_key=True),
    db.Column('project_id', db.Integer,
              db.ForeignKey('project.id'), primary_key=True)
)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    projects = db.relationship('Project', secondary=users_projects , lazy='dynamic',
                               back_populates='users')
    tasks = # What should I put here?

class Project(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)

    users = db.relationship('User', secondary=users_projects , lazy='dynamic',
                               back_populates='projects')
    tasks = db.relationship('Task', backref='project', lazy='dynamic')

class Task(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    project_id = db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)

我希望能够获得所有用户任务,以便我可以执行User.query.first().tasks.order_by(Task.due_date.desc()),这将需要多对多对多关系。我将如何建立这种关系?这是处理此查询的更好方法吗?

0 个答案:

没有答案