Reputation: 136
I am using flask-sqlalchemy in my application and have created below models. I am creating many to many relationship for Users and Subscription table, and tried to create helper table as User_Subscription. After creating this model, when i run db.create_all() in command line, it is creating only 3 tables in database (tables having db.Model) but not creating helper table (User_Subscription) at all. It is not giving any error either.
Could someone please advise what's going wrong here?
I already searched a lot on google and stackoverflow, but I can't find answer where anyone has faced this problem where helper table (via db.table()) is not being created. There was one issue from someone where they had somewhat similar problem, but he was facing as he wanted to do across multiple database. I am doing on same database.
class Subscription(db.Model):
__tablename__ = "subscription"
id = db.Column(db.Integer, primary_key=True)
subscription_name = db.Column(db.String(100), unique=True, nullable=False)
User_Subscription = db.table('user_subscription',
db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
db.Column('subscription_id', db.Integer, db.ForeignKey('subscription.id')),
db.Column('subscription_status', db.String(20), nullable=False, default='Active'))
class Users(db.Model, UserMixin):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(50), unique=False, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
date_updated = db.Column(db.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)
user_status_id = db.Column(db.String(2), db.ForeignKey('user_status.id'))
subscriptions = db.relationship('Subscription', secondary=User_Subscription, backref= db.backref('subscriptions', lazy=True))
def __repr__(self):
return f"Users('{self.firstname}', '{self.email}')"
class User_Status(db.Model):
__tablename__ = "user_status"
id = db.Column(db.String(2), primary_key=True)
status_desc = db.Column(db.String(20), unique=True, nullable=False)
users_status = db.relationship('Users', backref='usersofstatus')
Expected Result - 4 tables to be created in database.
Actual Result - Only 3 tables are being created. User_Subscription (Helper table for many to many relationship) is not being created.
Upvotes: 0
Views: 296
Reputation: 136
After few hours of frustration, i found that i had a typo, i was using db.table instead of db.Table. So posting this answer in case it can help someone.
Upvotes: 1
Reputation: 814
New to SQLAlchemy myself but it appears you are not inheriting from db.Model when creating User_Subscription. Why not make it a class?
class User_Subscription(db.Model):
Upvotes: 0