SQLAlchemy Object Missing when Null is returned - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: SQLAlchemy Object Missing when Null is returned (/thread-36431.html) |
SQLAlchemy Object Missing when Null is returned - Personne - Feb-19-2022 I'm learning Python and SQLAlchemy for the last 2 weeks, I made some progress but I'm having an issue I have no idea how to resolve. I do have a SQLAlchemy query as: query = db.session.query(Inventory, BLColor, BLCategory, BLPart, Location). \ join(BLColor, Inventory.color_id == BLColor.color_id). \ join(BLCategory, Inventory.category_id == BLCategory.category_id). \ join(BLPart, Inventory.part_id == BLPart.ITEMID). \ outerjoin(Location, Inventory.location_id == Location.loc_id,full=False). \ filter(Inventory.part_id == part_to_find, Inventory.userid == current_user.userid ).order_by(desc(Inventory.quantity)) dbparts = query.all()Later in my code I assign a variable with the result of this query such as: part_form.loc = p.Location.locationSo far all works, the problem arises when the location outer join return nothing. When everything work, when I look at the type and content of the dbparts variable, I see this dbparts=[(<Inventory 1206>, <BLColor 86>, <BLCategory 26>, <BLPart 3020>, <Location 96>), (<Inventory 1197>, <BLColor 11>, <BLCategory 26>, <BLPart 3020>, <Location 96>), (<Inventory 1201>, <BLColor 10>, <BLCategory 26>, <BLPart 3020>, <Location 96>), (<Inventory 1211>, <BLColor 5>, <BLCategory 26>, <BLPart 3020>, <Location 96>), (<Inventory 1198>, <BLColor 7>, <BLCategory 26>, <BLPart 3020>, <Location 96>), ...But when the location is blank I see this: <class 'list'> dbparts=[(<Inventory 1218>, <BLColor 11>, <BLCategory 479>, <BLPart 30200>, None]No more <Location ###> !!! Side question how are those <Inventory 1218>, <BLColor 11> , called ? So when I try to assign part_form.loc = p.Location.locationPython is errors out with the error message How do I treat this ?I'd like to do a: if p.Location.location exist then assign the value of part_form.loc = p.Location.location but if p.Location.location does not exist, set the value of part_form.loc = "UNKNOWN" RE: SQLAlchemy Object Missing when Null is returned - Larz60+ - Feb-19-2022 If you're too far into your project you may not wish to change, but using the ORM version of SQLAlchemy is more straight forward programming wise. I wrote a tutorial here that will show you the basics with a simple but complete package. Also take a look at pandas which does a great job for general database operations. See post: https://python-forum.io/thread-36430.html |