I have this to SQLAlchemy(using the Flask SqlAlchemy) objects defined:
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)
As I understand to add a friend I should be able to do something like this:
First getting the user:
MyUser = bpdata.User.query.filter_by(id=1).first()
Getting the friend:
MyFriend = bpdata.User.query.filter_by(id=2).first()
Now I would like to do:
MyUser.Friends.Append(MyFriend)
Is this possible or do I just have to add the friend IDs directly into the table Friend?
Figured this one out my self..
What I needed to do was:
MyUser.friends.append(Friend(MyUser.id, MyFriend.id))
and then commit the update.
Update:
Ok I found the proper way of doing what I wanted. First I don't need the Friend table/class at all. Full code:
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)
With this I can now do following:
>>> 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','[email protected]','2')>]
>>> user1.friends[0].added_by
[<User('admin','[email protected]','1')>]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With