G
G
Ganki2019-02-06 17:20:01
Flask
Ganki, 2019-02-06 17:20:01

How to get pictures from all albums and pass them to jinja template?

How to display 3 pictures from each album and pass them to the jinja template?
I can't figure out how to make a SQLAlchemy query.
Ways:

# routes.py

from app.models import User, Album, Image
from flask import render_template


@app.route('/')
def index():
    albums = Album.query.order_by(Album.timestamp.desc()).all()
    return render_template('index.html', albums=albums)

Database model:
# models.py

from app import db
from datetime import datetime


class Album(db.Model):
    __tablename__ = 'albums'
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    images = db.relationship('Image', backref='album', lazy='dynamic')


class Image(db.Model):
    __tablename__ = 'images'
    id = db.Column(db.Integer, primary_key=True)
    image_filename = db.Column(db.String)
    image_url = db.Column(db.String)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    album_id = db.Column(db.Integer, db.ForeignKey('albums.id'))

Sample:
# index.html

{% extends "base.html" %}

{% block app_content %}
  <h1>Albums</h1>
  {% for album in albums %}
      Id: {{ album.id }}

      ............................

  {% endfor %}
{% endblock %}

I want it to be displayed in the browser like this:
5c5aece1afaf4638044107.pngAdditions:
I partially managed to solve the problem by changing the "index.html" template file:
{% extends "base.html" %}

{% block app_content %}

  {% for album in albums %}
    <h1>Album ID: {{ album.id}}</h1>
    {% for photo in album.images %}
      {{ photo.image_url }} <br>
    {% endfor %}
  {% endfor %}

{% endblock %}

But the page displays all the pictures, all the albums. And it is necessary that only the first 3 pictures of each album be displayed, and the album should not be displayed if there are no photos in it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2019-02-25
@Ganki

{% for album in albums %}
{% if album %}
Album ID: {{ album.id}}
{% for photo in album.images %}
{% if loop.index < 4 %}
{{ photo.image_url } }
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}

P
pcdesign, 2019-02-06
@pcdesign

If you want to pull out both albums and pictures with one request, then something like this:

q = db.session.query(Album,  Image).join(Image).filter(Album.id==Image.album_id)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question