0
votes

I have a MyModel object which inherits from Model from SQLAlchemy. Accessing the primary key (ID) seems to take much longer than any other attribute:

value = getattr(model, ID)

takes ~1.4ms to compute or get the value of but,

value = getattr(model, <any_other_column>)

takes exponentially less time to get the value of that column no matter what type it may be? Is there a faster way to get the primary key value from a Model object?

1

1 Answers

3
votes

Enable SQLAlchemy debugging and see what SQL queries that are executed. My assumption is that you have an object that is expired according to SQLAlchemy and when you try to get the first attribute, it has to read the data from the database. When you do the same thing again (on any attribute), it should be fast again. This kind of situation normally happens if you fetch some objects from the database, commit the session and then try to use the previously fetched objects again. This is happening because on commit, SQLAlchemy doesn't know if other transactions did not modify the data, so it has to fetch them again.