Blankman
Blankman

Reputation: 266910

Simply sqlalchemy filter not working

Select all works like this:

q = session.query(products)

Now I want to add a WHERE filter, so I am trying:

q = session.query(products).filter_by(stock_count=0)

I get an error saying 'nonetype' object has no attribute 'class_manager'.

Not sure what the issue is?

Update The column seems to be mapped fine, as when I do:

q = session.query(products)

for p in q:
   print p.stock_count

It outputs the value.

But if I do:

p.stock_count = 6

I get an error also, saying: "can't set attribute"

So I can query for it, but adding the column as a filter, OR setting the value causes an error.

Strange no?

Upvotes: 3

Views: 7548

Answers (4)

mikefedyk
mikefedyk

Reputation: 21

You may be trying to use the orm against a bare Table object.

This code works on 0.5 (the one in base centos 6.2):

#!/usr/bin/env python
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

db = create_engine(localopts.connect_string)
Session = sessionmaker(bind=db)

Base = declarative_base()
Base.metadata.reflect(bind=db)

class some_table(Base): 
    __table__ = Base.metadata.tables['table_name']

session = Session()

for row in session.query(some_table.username).filter_by(username="some-user"):
    print row

Upvotes: 2

knitti
knitti

Reputation: 7033

filter_by() works with a keyword dictionary, you actually want to use filter(). Additionaly you can't just use stock_count (probably, you didn't show your table definition code), you have to use products.stock_count or possibly products.__class__.stock_count. So Try: q=session.query(products).filter(product.stock_count==0)

Upvotes: 0

Eugen
Eugen

Reputation: 2820

Have you tried Literal Sql? I've had the same error message but when I used literal sql it was gone.

So for your example it would be something like:

q = session.query(products).filter('stock_count==0')

Upvotes: 0

dls
dls

Reputation: 4146

have you tried adding a .all() after your filter_by:

q = session.query(products).filter_by(stock_count=0).all()

Upvotes: 0

Related Questions