Skip to content
Advertisement

How to filter and display flask sqlalchemy one to many relationship data with jinja

I have two mysql tables (“song_info” and “djartist1”) which they have one to many relationship. I want to display the all songs from a single artist (all posts from a specific user). But I’m getting a list, instead of what I want to be displayed on the html file. Can you give me a solution please ?.

here are the codes related to this issue

JavaScript

This is the html code

JavaScript

This is the html output I’m getting

JavaScript

Above numbers are correct. But what I need is the name of the song of those numbers (ID’s).

Jinja2 HTML code and the output

Advertisement

Answer

You need to specify which attributes you want to see, currently you’re referencing an entire object, not a string or integer, and that is also what’s being represented.

JavaScript

There are a few more notes to give on this:

Are the artist slugs unique? Because it looks like you have multiple artists with the same slug and each artist has one song. It would make more sense to have one song with an artist_id and an artist relationship, and then give the artist a songs attribute. Here is an example:

JavaScript

Besides, if you have only one Djartist per slug, then you don’t need to do multiple queries. You can change your view function to

JavaScript

And reference songs in the template through {% for song in artist.songs} %}

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement