Search code examples
pythonpython-3.xflasksqlalchemyflask-sqlalchemy

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.


Solution

  • 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()