Pregunta

While trying to learn Flask, I am building a simple Twitter clone. This would include the ability for a User to follow other Users. I am trying to set up a relational database through SQLAlchemy to allow this.

I figured I would need a self-referencing many-to-many relationship on the User. Following from the SQLAlchemy documentation I arrived at:

#imports omitted    

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///twitclone.db'
db = SQLAlchemy(app)

Base = declarative_base()

user_to_user = Table("user_to_user", Base.metadata,
    Column("follower_id", Integer, ForeignKey("user.id"), primary_key=True),
    Column("followed_id", Integer, ForeignKey("user.id"), primary_key=True)
)

class User(db.Model):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String, unique=False)
    handle = Column(String, unique=True)
    password = Column(String, unique=False)
    children = relationship("tweet")
    following = relationship("user",
                    secondary=user_to_user,
                    primaryjoin=id==user_to_user.c.follower_id,
                    secondaryjoin=id==user_to_user.c.followed_id,
                    backref="followed_by"
    )

#Tweet class goes here

db.create_all()

if __name__ == "__main__":
    app.run()

Running this code results in the database being created without any error messages. However, the whole part (table) connecting a user to a user is simply omitted. This is the definition of the User table:

CREATE TABLE user (
    id INTEGER NOT NULL, 
    name VARCHAR, 
    handle VARCHAR, 
    password VARCHAR, 
    PRIMARY KEY (id), 
    UNIQUE (handle)
)

Why does SQLAlchemy not create the self-referential relationship for the User?

note: I am new to both Flask and SQLAlchemy and could be missing something obvious here.

¿Fue útil?

Solución

Ok, it seems I mixed up two different styles of using SQLAlchemy with Flask: the declarative extension of SQLAlchemy and flask-sqlalchemy extension. Both are similar in capabilities with the difference being that the flask extension has some goodies like session handling. This is how I rewrote my code to strictly make use of flask-sqlalchemy.

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///kwek.db'
db = SQLAlchemy(app)

#Table to handle the self-referencing many-to-many relationship for the User class:
#First column holds the user who follows, the second the user who is being followed.
user_to_user = db.Table('user_to_user',
    db.Column("follower_id", db.Integer, db.ForeignKey("user.id"), primary_key=True),
    db.Column("followed_id", db.Integer, db.ForeignKey("user.id"), primary_key=True)
)


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=False)
    handle = db.Column(db.String(16), unique=True)
    password = db.Column(db.String, unique=False)
    kweks = db.relationship("Kwek", lazy="dynamic")
    following = db.relationship("User",
                    secondary=user_to_user,
                    primaryjoin=id==user_to_user.c.follower_id,
                    secondaryjoin=id==user_to_user.c.followed_id,
                    backref="followed_by"
    )

    def __repr__(self):
        return '<User %r>' % self.name


class Kwek(db.Model):
    __tablename__ = 'kwek'
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(140), unique=False)
    post_date = db.Column(db.DateTime, default=datetime.now())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return '<Kwek %r>' % self.content

if __name__ == "__main__":
    app.run()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top