Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have this code querying for some objects from my database with Flask-SQLAlchemy:

areas = Area.query.all()
subareas = Subarea.query.all()

And then I use it on html with Jinja template to display data:

{% for area in areas %}
    {% if area.number=='0' %}
        <select id="{{ area.number }}" class="subarea" onchange="ChangeDropdowns(this.value)">
    {% else %}
        <select id="{{ area.number }}" class="subarea" style="display: none;" onchange="ChangeDropdowns(this.value)">
    {% endif %}
        <option value="" disabled="disabled" selected="selected">Escolha uma Subárea</option>
    {% for subarea in subareas%}
        {% if subarea.areaNumber == area.number %}
            {% if subarea.disabled %}
                <option value="{{ subarea.number }}" disabled="disabled">{{ subarea.view }}</option>
            {% else %}
                <option value="{{ subarea.number }}">{{ subarea.view }}</option>
            {% endif %}
        {% endif %}
    {% endfor %}
    </select>
{% endfor %}

Database models:

class Area(db.Model):
areaID = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
number = db.Column(db.String(1))
view = db.Column(db.String)
disabled = db.Column(db.Boolean)

def __init__(self, name, number, view, disabled):
    self.name = name
    self.number = number
    self.view = view
    self.disabled = disabled


class Subarea(db.Model):
subareaID = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
number = db.Column(db.String(2))
view = db.Column(db.String)
disabled = db.Column(db.Boolean)
areaNumber = db.Column(db.String(1))

def __init__(self, name, number, view, disabled, areaNumber):
    self.name = name
    self.number = number
    self.view = view
    self.disabled = disabled
    self.areaNumber = areaNumber

Firstly, I would like to have subareas as a dictionary or a list of lists, that way I don't need to iterate areas length times over all subareas length.

But will that really improve the code? How many entries do I need to have on my database to see a substantial difference in time? Is there another way to improve this template?

share|improve this question
    
Can you post the model you use for Area and SubArea in theory, there must be a FK between SubArea and Area and you can prefetch and access SubArea instance from Area instance – amirouche Aug 23 at 12:45
    
Sure. I have just updated the question. Since it is my first time using a database I couldn't really get how a FK works on the relationship() function with backref. – 0rkan Aug 23 at 12:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.