4

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?

1
  • I think you are creating wrong relationship. One user has many friends and same friend can be friend in many user so you have to use M2M instead of O2M. Commented Mar 5, 2012 at 5:24

1 Answer 1

10

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')>]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.