0

Flask view function

@app.route("/articles/<a_id>")
def articles(a_id):
    article = get_article(a_id)
    if article is None:
        return render_template_with_options("404.html")

    paragraphs = get_paragraphs(a_id)

    return render_template_with_options(
        "article.html",
        article=article,
        paragraphs=paragraphs,
    )

crud function get_paragraphs

def get_paragraphs(article_id: int):
    db = next(db_session())
    data = db.scalars(
        select(Paragraph)
        .where(Paragraph.article_id == article_id)
        .order_by(Paragraph.order)
    ).all()
    return data

Part of HTML file "article.html" where Error raised

{% for p in paragraphs%}
        <h2 class="article-sub-title mb-2 mt-4">{{p.title}}</h2>
    {% if p.Image %}
        <img
          class="img-fluid image-cover image-wide"
          src="{{p.Image.small_img}}"
          style="max-width: 700px; max-height: 500px"
        />
    {% endif %}
        <p class="mb-5 mt-3">{{ p.content|safe}}</p>
{% endfor %}

Error message

sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Paragraph at 0xffff819b9160> is not bound to a Session; lazy load operation of attribute 'Image' cannot proceed (Background on this error at: https://sqlalche.me/e/20/bhk3)

Code which makes the error

{% if p.Image %}

I find this error from ever first access to the webpage in localhost. The thing that I can not understand is when I refresh the webpage that is saying the error message, The error message just disappears.

In local env, that makes error message but in product env, that returns server error.

What is the reason and how can I fix it?

David kim
  • 180
  • 1
  • 1
  • 11
  • The problem is that you are trying to access a related object (`Paragraph.Image`) outside a session. The related object was not loaded when the `Paragraph` was loaded, and it cannot be loaded without a session (see the linked duplicate). Adding `.options(orm.selectinload(Paragraph.Image)` to the `select` should fix it. See [here](https://docs.sqlalchemy.org/en/20/orm/queryguide/relationships.html#select-in-loading) and more generally [here](https://docs.sqlalchemy.org/en/20/orm/queryguide/relationships.html#relationship-loading-techniques). – snakecharmerb Aug 12 '23 at 16:20

0 Answers0