flask sqlalchemy query with keyword as variable

SQLAlchemy’s filter_by takes keyword arguments: filter_by(**kwargs) In other words, the function will allow you to give it any keyword parameter. This is why you can use any keyword that you want in your code: SQLAlchemy basically sees the arguments a dictionary of values. See the Python tutorial for more information on keyword arguments. So that … Read more

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

Using SQLAlchemy models in and out of Flask

flask_sqlalchemy doesn`t allow you to use it outside of a Flask context. However, you can create models via SQLAlchemy itself. So your database.py file would look like this: from sqlalchemy import MetaData, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base metadata = MetaData() Base = declarative_base(metadata=metadata) class Job(Base): __tablename__ = ‘job’ job_id = Column(Integer, primary_key=True) description … Read more

Flask-SQLAlchemy Constructor

In most cases not defining a constructor in your model class gives you the correct behavior. Flask-SQLAlchemy’s base model class (which is also SQLAlchemy’s declarative base class) defines a constructor that just takes **kwargs and stores all the arguments given, so it isn’t really necessary to define a constructor. If you do need to define … Read more