Home > OS >  How to separate database on 2 different table html
How to separate database on 2 different table html

Time:04-26

i have database for example

id account_id date
1 127 2022-04-25
2 128 2022-04-25
3 127 2022-04-24
4 128 2022-04-24

And i need separate this on 2 different tables:

account_id date header
127 2022-04-25
127 2022-04-24

and the same with 128

That's my code for 1 table and i don't know how to separate

@bp.route('/')
def main():
    wcms = Wcm.query.order_by(Wcm.date.desc()).all()
    return render_template('table.html', wcms=wcms)

HTML:

<table >
        <thead>
            <tr>
                <th>Date</th>
                <th>WCM account ID</th>
                <th>Number of standard tags</th>
                <th>Number of extended tags</th>
            </tr>
        </thead>
        <tbody>
            {% for wcm in wcms %}
                <tr>
                    <td>{{ wcm.date }}</td>
                    <td>{{ wcm.account_id }}</td>
                    <td>{{ wcm.nbm_stardart_tags }}</td>
                    <td>{{ wcm.nbm_custom_tags }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

CodePudding user response:

For the following code to work we need to sort the data by the grouping value first. Since you want to seperate account IDs, I chose ASC.

wcms = Wcm.query.order_by(Wcm.account_id.asc(), Wcm.date.desc()).all()

The lambda returns the account ID to collect all entries into one list. groupby returns a list of tuples, the list() call is needed to evaluate the lazy iterator creating the group. The outer list comprehensions creates a list of those grouped Wcm lists.

wcms_by_account = [
    list(wcm_group) 
    for acc_id, wcm_group 
    in groupby(wcms, lambda x: x.account_id
]

List strucure:

[
    [
        Wcm(account_id=127, date=2022-04-25, ...),
        Wcm(account_id=127, date=2022-04-24, ...),
    ],
    [
        Wcm(account_id=128, date=2022-04-25, ...),
        Wcm(account_id=128, date=2022-04-24, ...),
    ],
    ...
]

Then change your Web Template to handle a list of lists, creating a new table for each inner list.

{% for wcms in wcms_by_account %}
  <table >
        <thead>
            <tr>
                <th>Date</th>
                <th>WCM account ID</th>
                <th>Number of standard tags</th>
                <th>Number of extended tags</th>
            </tr>
        </thead>
        <tbody>
            {% for wcm in wcms %}
                <tr>
                    <td>{{ wcm.date }}</td>
                    <td>{{ wcm.account_id }}</td>
                    <td>{{ wcm.nbm_stardart_tags }}</td>
                    <td>{{ wcm.nbm_custom_tags }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
{% endfor %}
  • Related