Reputation: 1925
I am a beginner trying to execute a simple web application using Pyramid and SQLAlchemy. As of now my app just returns all data stored in my table.
My views.py:
@view_config(route_name='home', renderer='templates/trial.pt')
def my_view(request):
try:
#str=Mystring(name="second",data="Hellostring")
#DBSession.add(str)
myvar=Mystring.query.order_by(Mystrings.data)
except DBAPIError:
return Response(conn_err_msg, content_type='text/plain', status_int=500)
#return {'project': 'Alpy'}
return {'myvar':myvar}
My template:-
<body>
<div id="middle">
<div class="middle align-right">
<div id="left" class="app-welcome align-left">
You can return to the
<a href="${request.application_url}">FrontPage</a>.<br/>
<div tal:condition="myvar">
Your selection returns:<br><tal:block tal:content="myvar"></tal:block>
</div>
</div>
</div>
</body>
my model.py:-
class Mystring(Base):
__tablename__ = 'mystrings'
id = Column(Integer, primary_key=True)
name = Column(Text)
data = Column(Text)
My error is: AttributeError: type object 'Mystring' has no attribute 'query'
I tried this. "myvar=DBSession.query(Mystring).all()" the error went away but I get
Your selection returns:
[alpy.models.Mystring object at xxxx, alpy.models.Mystring object at xxxxx]
which is not what i intended to get. I wanted a name value pair.
Please help.
Upvotes: 1
Views: 207
Reputation: 402
You are getting a list of objects from sqlalchemy. If you just need the data, and you want to return a list of (name, data) pairs, you can do it with a list comprehension like this:
return [(x.name, x.data) for x in myvar]
Note: x
is just a local variable for the list comprehension, so it can be any name you like.
There is some great documentation for sqlalchemy basics at the official site, here: http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html
Upvotes: 2