flask-sqlalchemy icon indicating copy to clipboard operation
flask-sqlalchemy copied to clipboard

how to let flask-sqlalchemy's query object select columns ( or say fields )?

Open iceblove opened this issue 15 years ago • 3 comments

hi, Armin,

I met some problem that wired me the whole day. I'm using flask/flask-sqlalchemy/postgresql, and I want to do this:

published_sites = msg_published.query
.filter( and_(*filter_clause) )
.group_by( msg_published.site_id )
.order_by( order_clause )
.paginate( page_no, per_page, error_out = False ) but in mysql, it is OK, and in postgresql it is wrong and ask for the other fields besides site_id either in a group by clause or in a aggregation function, I know that postgresql is stricter on SQL than mysql , so I must select the site_id in the query object of msg_published, but in pure sqlalchemy I can do like this:

published_sites = session.query( msg_published.site_id )
.filter( and_(*filter_clause) )
.group_by( msg_published.site_id )
.order_by( order_clause )
.paginate( page_no, per_page, error_out = False ) and in flask-sqlalchemy, how to get it work?

iceblove avatar Aug 27 '11 12:08 iceblove

your_model_object.query.with_entities(Your_model.your_attribute)

ferhatelmas avatar Nov 19 '13 15:11 ferhatelmas

I used sqlite3

CREATE TABLE "thread" (	`id`	INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT )
INSERT INTO `thread`(`id`) VALUES (1);

Here it's my DB model

class Thread(db.Model):
      id = db.Column(db.Integer, primary_key=True)

And code to select any row from database

threads = Thread.query.filter_by(id='1')

madtune avatar Dec 30 '17 16:12 madtune

Is there a way to make a query without the Model object? Let's say I 've already some data pre-populated in my postgres database?

irmscher9 avatar Dec 06 '18 17:12 irmscher9