I
I
Ilya Demyanov2017-04-03 11:57:26
Flask
Ilya Demyanov, 2017-04-03 11:57:26

How to optimize the number of requests in a template?

There are two related models:

class Contact(db.Model):
    __tablename__ = 'contacts'
    id = db.Column(db.Integer, primary_key=True)
    full_name = db.Column(db.String(255), nullable=False)
    phones = db.relationship('Phone',
                             backref='contact', lazy='dynamic',
                             order_by='Phone.priority, Phone.phone_number')


class Phone(db.Model):
    __tablename__ = 'phones'
    phone_number = db.Column(db.String(10), primary_key=True)
    phone_type = db.Column(db.Integer)
    contact_id = db.Column(db.Integer,
                           db.ForeignKey('contacts.id'),
                           nullable=False)

phone_types = {
    'Internal': 1,
    'External': 2,
    'Mobile': 3,
    'Radio': 4,
}


Now the contact output in the template inside the table looks like this:

<tr>
    <td>{{ contact.full_name }}</td>
    {%- for phone_type_key, phone_type_value in phone_types|dictsort(by='value') -%}
        <td>
            {%- for phone in contact.phones if phone.phone_type == phone_type_value -%}
            {{ phone.phone_number }}<br>
            {%- endfor -%}
        </td>
    {%- endfor -%}
</tr>


Those. a separate query is generated for each phone_type column. Is it possible to optimize this somehow?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question