SQLAlchemy ordering by count on a many to many relationship

I haven’t used SQLAlchemy much so I figured I’d give it a shot. I didn’t try to use your models, I just wrote some new ones (similar enough though): likes = db.Table(‘likes’, db.Column(‘user_id’, db.Integer, db.ForeignKey(‘user.id’)), db.Column(‘post_id’, db.Integer, db.ForeignKey(‘post.id’)) ) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20)) def __repr__(self): return “<User(‘%s’)>” % self.username class … Read more

Circular import of db reference using Flask-SQLAlchemy and Blueprints

I fixed the problem with the help of the Application Factory pattern. I declare the database in a third module and configure it later in the same module in which I start the application. This results in the following imports: database.py → app.py views.py → app.py database.py → views.py There is no circular import. It … Read more

Getting first row from sqlalchemy

Use query.one() to get one, and exactly one result. In all other cases it will raise an exception you can handle: from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import MultipleResultsFound try: user = session.query(User).one() except MultipleResultsFound, e: print e # Deal with it except NoResultFound, e: print e # Deal with that as well There’s also … Read more

Tyring to set up modelview with Flask-Admin causes ImportError

Your code has the line from app.models import User in __init__.py. The problem is that app.models has from . import db. This is a circular import: __init__ tries to import User, which tries to import db, which isn’t defined until after __init__ tries to import User. To solve this, move your local app imports below … Read more

Flask sqlalchemy many-to-many insert data

You don’t need to add anything directly to your association table, SQLAlchemy will do that. This is more or less from SQLAlchemy documentations: association_table = db.Table(‘association’, db.Model.metadata, db.Column(‘left_id’, db.Integer, db.ForeignKey(‘left.id’)), db.Column(‘right_id’, db.Integer, db.ForeignKey(‘right.id’)) ) class Parent(db.Model): __tablename__ = ‘left’ id = db.Column(db.Integer, primary_key=True) children = db.relationship(“Child”, secondary=association_table) class Child(db.Model): __tablename__ = ‘right’ id = db.Column(db.Integer, … Read more

SQLAlchemy ManyToMany secondary table with additional fields

You will have to switch from using a plain, many-to-many relationship to using an “Association Object”, which is basically just taking the association table and giving it a proper class mapping. You’ll then define one-to-many relationships to User and Community: class Membership(db.Model): __tablename__ = ‘community_members’ id = db.Column(‘id’, db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey(‘user.id’)) community_id … Read more

tech