Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get position of object in flask query .all()

I would like to know how can I get the position of some object in a list of objects from flask sqlalchemy.

universities = University.query.order_by(University.students_total.desc()).all()

print universities
[<University 38>, <University 34>, <University 19>, <University 33>]

Let’s say I want to get the position of the University 19

I’ve tried this, without success: universities.index("<University 19>")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ValueError: '<University 19>' is not in list

>Solution :

You could do this by querying for a university and then finding the index of that university in your list of all universities. This could look something like this:

selected_university = University.query.filter_by(id=19).first()
universities.index(selected_university)

The problem with your previous code was that printing a list of all universities displayed the string representation of each object. You were then trying to find the index of one of those string representations. This didn’t work because the actual list contained objects, not strings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading