2

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?

1 Answer 1

2

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 :

  1. define the schema, with Tables, Columns and Constraints
  2. define the relationship that ties the Python classes together

In 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Agreed. If you have a DBA on your team you should consult with the DBA.

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.