8
8
891099838382014-12-18 07:12:07
Flask
89109983838, 2014-12-18 07:12:07

How to select fields from database to create site menu without unnecessary columns in Flask-SQLAlchemy?

I have such a function to select all posts to generate a menu

@app.context_processor
def menu():
    articles = Article.query.filter_by(onoff=1).all()
    return dict(articles=articles)

Considering that the menu on all pages of the site is "wrapped" in a context processor that starts every time the site is accessed, and passes all posts to the template engine.
This is how it works - but the problem is that in addition to the necessary information (post title, CNC link, serial number), a bunch of unnecessary information is uploaded for the above purpose (for example, the articles themselves on the pages ...... :) - what I think is "not there is Hood!

How to form a query in such a way as to filter out unnecessary columns and leave only rows: post title, NC link, ordinal number.

filter_by(onoff=1) = this is a filter, only upload flagged posts.
(7 times I try to figure out the mana to SQLAlchemy - something with the translation does not work out well for me).

Thank you in advance!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
denself, 2015-01-02
@89109983838

I'm not sure if this code will work wrapped with Flask, but in SQLAlchemy it's done something like this:
Such an instruction will return a list of tuples of the form:

[("name1", "url1", "num1"), ("name2", "url2", "num2"), ... ]

8
89109983838, 2014-12-18
@89109983838

from sqlalchemy.orm import load_only

@app.context_processor
def menu():
    articles = Article.query.filter_by(onoff=1).options(load_only("name", "url", "num"))
    return dict(articles=articles)

I tried this... the site seems to be working! :) - there is no time to see from the interactive mode what exactly is being unloaded there... then return to this question, check, unsubscribe...
################ added after a long time.. #####################
and so if you put {{ articles }} somewhere in the template, then in html there is this line:
if in the menu generation instead of the link text set the field names where the article code is stored
{% for article in articles %}
        <li><a href="/{{ article.url }}/">{{ article.article }}</a></li>
{% endfor %}

then instead of names there is a huge set of texts (well, the articles themselves .....)
and if you still do this, then generally ATAS! ;)
{% for article in articles %}
        <li><a href="/{{ article.url }}/">{{ article.article|safe }}</a></li>
{% endfor %}

So the question remains open.......

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question