使用SQLAlchemy将数据添加到相关表

时间:2012-03-03 15:32:45

标签: python sqlalchemy

我有这个SQLAlchemy(使用Flask SqlAlchemy)定义的对象:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True)
    password = db.Column(db.String(30))
    email = db.Column(db.String(45), unique=True)
    friends = db.relationship('Friend', backref='user',
                                lazy='dynamic')

    def __init__(self, username, password, email):
        self.username = username
        self.password = password
        self.email = email

    def __repr__(self):
        return "<User('%s','%s','%s')>" % (self.username, self.email, self.id)


class Friend(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    userId = db.Column(db.Integer, db.ForeignKey('user.id'))
    friendId = db.Column(db.Integer)
    created = db.Column(db.DateTime)

    def __init__(self, userId, friendId):
        self.userId = userId
        self.friendId = friendId
        self.created = datetime.datetime.now()

    def __repr__(self):
        return "<Friend(%i,%i)>" % (self.userId, self.friendId)

据我了解添加朋友,我应该能够做到这样的事情:

首先得到用户:

MyUser = bpdata.User.query.filter_by(id=1).first()

结识朋友:

MyFriend = bpdata.User.query.filter_by(id=2).first()

现在我想做:

MyUser.Friends.Append(MyFriend)

这是可能的还是我只需要将朋友ID直接添加到朋友表中?

1 个答案:

答案 0 :(得分:8)

想出这个我的自我......

我需要做的是:

MyUser.friends.append(Friend(MyUser.id, MyFriend.id))

然后提交更新。

<强>更新

好的,我找到了做我想要的正确方法。首先,我根本不需要朋友表/班级。完整代码:

association_table = db.Table('association',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('friend_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True)
    password = db.Column(db.String(30))
    email = db.Column(db.String(45), unique=True)
    friends = db.relationship("User",
                secondary=association_table,
                backref='added_by',
                primaryjoin=id == association_table.c.user_id,
                secondaryjoin=id == association_table.c.friend_id)

有了这个,我现在可以做到:

>>> user1 = User.query.filter_by(id=1).first()
>>> user1.friends
[]
>>> user2 = User.query.filter_by(id=2).first()
>>> user1.friends.append(user2)
>>> user1.friends
[<User('user1','user1@admin.com','2')>]
>>> user1.friends[0].added_by
[<User('admin','admin@admin.com','1')>]