Reputation: 866
I have the following code:
@staticmethod
def get_all_locations_for_event(value):
sql = text('SELECT * \
FROM public.location_event \
INNER JOIN public.location \
ON public.location_event.location_id = public.location.id \
WHERE event_id = :x;')
result = db.engine.execute(sql, x = value)
for r in result:
dict_ = dict(r)
return dict_
It only returns the first row. However I would like it to return all results. I am new to SQL-Alchemy so forgive me if I am missing something. I have searched online for the past couple of hours and so far I have only ran across code samples that return a single row, not multiple rows.
I know the issue is with the for loop as it is not iterating enough times to get the rest of the data, however I am not certain what the fix would be seeing result is an object.
P.S. If this can be done in an ORM method, I am all ears as well. I decided to use SQL because I couldn't get my ORM model to select the correct data.
Upvotes: 1
Views: 1284
Reputation: 8002
I'm guessing you can do something like (untested and depends on your model):
Location.join(LocationEvent).filter_by(event_id=**value**).all()
Join requires relavant foreign key
Upvotes: 0
Reputation: 1842
I think you're right that the issues lies with your for-loop. It is unclear what you intend dict_ to be but at present, each iteration overwrites it. dict_ will hold the values of your result from the final iteration before it exited.
If I'm not mistaken, your result is already an attributed object (Please correct me if I'm wrong on this) i.e. you should be able to access the corresponding database columns through the dot notation. Therefore, you should be able to loop through the items like:
Example
dict_ = []
for r in result:
id = r.id
name = r.name
dict_.append((id,name))
Upvotes: 0
Reputation: 52929
Your for loop is iterating just the right amount of times, but in its body you repeatedly rebind the name dict_
to a new dict
instance, and so your function returns the very last result produced by your query. Instead you'll want to return a list, or turn your function to a generator:
def get_all_locations_for_event(value):
...
result = db.engine.execute(sql, x = value)
return result.fetchall()
For most purposes there is no need to explicitly convert the RowProxy
instances of the result to dict
, since they act as ordered maps on their own. A notable exception is serializing to JSON, since the json
module does not know how to handle SQLAlchemy row proxies.
Upvotes: 2