Hi Simon, thanks for the help! I've never used that before, it's quite handy.
I'm looping through all the students and printing them and their subject details to a CSV file.
What makes things a tad complicated is the subjects must appear in a specific order.
There is a table that has the subject code and order number (ordered_subjects used below is the resultset from it).
I printed out the timing and found the problem to be with a nested for loop.
I was hoping to reduce that process time by using a map that automatically gets populated instead of having to create it on the fly.
Before - subjects_collection "attribute_mapped_collection":
********************************************************************************************
for row in students:
row_no += 1
for subject in row.subjects:
student_subjects[subject.code] = subject.value
csv_row = [row_no]
csv_row += [student_subjects.get(x.code, '') for x in ordered_subjects]
csv_row += [row.created_on, row.updated_on]
writer.writerow([x.encode('utf-8') if type(x) == unicode else x for x in csv_row])
After adding the subjects_collection "attribute_mapped_collection", I unfortunately did not see a change in performance.
After - subjects_collection "attribute_mapped_collection":
********************************************************************************************
for row in students:
row_no += 1
csv_row = [row_no]
csv_row += [row.subjects_collection.get(x.code, '').value for x in ordered_subjects]
csv_row += [row.created_on, row.updated_on]
writer.writerow([x.encode('utf-8') if type(x) == unicode else x for x in csv_row])
class Subject(db.Model):
__tablename__ = 'subjects'
student_id = db.Column(db.Integer, db.ForeignKey('
students.id'), primary_key=True)
code = db.Column(db.String(50), primary_key=True)
value= db.Column(db.String)
def __init__(self, code , value):
self.code = code
self.value = value
class Student(ResourceMixin, db.Model):
__tablename__ = 'students'
subjects= db.relationship('Subject', backref='student')
id = db.Column(db.Integer, primary_key=True)
subjects_collection = relationship("Subject", collection_class=attribute_mapped_collection('code'))
Can you see a way I can optimize this? Any ideas?