Reputation: 247
So I have a class defined as follows:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
hashed_password = db.Column(db.String(100))
friends = db.relationship('User',
backref='user', lazy='dynamic')
def __init__(self, username, email, hashed_password):
self.username = username
self.email = email
self.hashed_password = hashed_password
def __repr__(self):
return '<User %r>' % self.username
Essentially, I want each User to have a list of Users (their friends), but I can't seem to find out if this is the right way to model this relationship and, if it seems reasonable, how would I go about inserting a new User as a friend into this list for another given User?
Upvotes: 2
Views: 207
Reputation: 10938
You need to look at your problem from the database schema perspective and then write the SQLAlchemy code to generate that schema. This is important because SA abstracts little out of the schema generation and the ORM is a separate component (this is one of the best aspects SQLAlchemy). Using the declarative extension does not make this distinction go away.
Specifically, you are declaring a relationship
, which is an ORM construct, without any underlying column and foreign-key constraint. What you need to do is :
Table
s, Column
s and Constraint
srelationship
that ties the Python classes togetherIn this case, you want a many-to-many relationship between users, so you'll need a secondary table with (at least) two columns, both foreign keys to the users table. This case is well covered by the SQLAlchemy docs, including the tutorials.
Upvotes: 2