Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlalchemy - add columns to a query

For example I am using the chinook database and I would like to convert the Name field into a slug. Slugify is a function from awesome-slugify.

Something like this in SQL

Select *, slugify(Name) as name_slug
from Artist

In sqlalchemy I have tried:

artist = Artist.query.add_columns(name_slug=slugify(Artist.Name)).all()

and

artist = Artist.query.add_columns(name_slug=[slugify(a.Name) for a in Artist.Name]).all()

I can generate a list of name slugs by doing to following in the terminal:

art = models.Artist.query.all()
name_slug = [slugify(a.Name) for a in art]
print(name_slug)

But I am not certain how to tie it all together.

like image 350
spitfiredd Avatar asked Jan 12 '17 01:01

spitfiredd


People also ask

What does all () do in SQLAlchemy?

all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present.

Is SQLAlchemy good for ETL?

One of the key aspects of any data science workflow is the sourcing, cleaning, and storing of raw data in a form that can be used upstream. This process is commonly referred to as “Extract-Transform-Load,” or ETL for short.

What is subquery in SQLAlchemy?

The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.


1 Answers

I don't have slugify to test, but this is probably what you are looking for:

artist = Artist.query.add_columns(slugify(Artist.Name).label("name_slug")).all()
like image 79
juanitogan Avatar answered Sep 20 '22 13:09

juanitogan