AllenP
AllenP

Reputation: 25

SQLAlchemy attribute error when filtering by list attributes

After searching and trying different things I can't seem to figure out what I'm doing wrong here. What I intended to happen was fill orderServicesFull with a Services object filled with database data filtered by the serviceID of orderServices.

The issue I'm running into is I cannot seem to find the correct syntax for pulling each instance of serviceID from orderServices (second line of code).

orderServices = DBSession.query(ServicesByOrder).filter(ServicesByOrder.orderID == request.GET['orderID']).all()

orderServicesFull = DBSession.query(Services).filter(Services.serviceID == orderServices.serviceID).all()

Error:

AttributeError: 'list' object has no attribute 'serviceID'

What I've tried:

In my attempt to solve this I first did a few prints to understand what was being passed. I also looked at some documentation to try understanding what was appropriate. I even tried this... lol

print("<---DEBUG--->")
    serviceIDs = []
    for i in range(0, len(orderServices)):
        serviceIDs.append(orderServices[i].serviceID)
        print(serviceIDs[i])

The idea behind this was that it was a simple list and I could work with it easier. I attempted to use that instead of the orderServices list. As you can guess that did not work either.

Any thoughts or suggestions would be greatly appreciated.

Thanks for your time

!SOLVED!

Well after much messing around and some more research I came up with a solution. It may not be as efficient as someone else could have came up with but it works.

My problem was coming from the fact that I wasn't aware that the list was filled with objects.

orderServiceList = DBSession.execute(\
"SELECT s.serviceID, s.serviceName, s.serviceCost "+\
"FROM tblServicesByOrder AS so "+\
"INNER JOIN tblServices AS s "+\
"ON so.serviceID = s.serviceID "+\
"WHERE so.orderID = 1").fetchall()

orderServicesFull = [row for row in orderServiceList]

Doing this allowed me to create a dictionary list with the data I needed and then from there fill my orderServicesFull.

I hope this helps someone else having this same issue or similar.

Upvotes: 2

Views: 1317

Answers (1)

van
van

Reputation: 77082

From your first code snippet, the orderServices variable is in fact a list. Therefore, you cannot use orderServices.ID in the second query (the error you get explains that).
You should be able to get all the services using ORM query with a join:

orderServicesFull = (DBSession.query(Services)
    .join(ServicesByOrder, Services.serviceID == ServicesByOrder.serviceID)
    .filter(ServicesByOrder.orderID == request.GET['orderID'])
    ).all()

If you have a (just one) relationship defined between Services and ServicesByOrder, then the join does not require the clause parameter and becomes .join(ServicesByOrder)

Upvotes: 1

Related Questions