1

The following is a screenshot of my code and database table data:

from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('mssql+pymssql://sa:12345678@XXXX:1433/YYYY')
Base = declarative_base(engine)


 class User(Base):

    __tablename__ = 'Products'

    Id = Column(String(20), primary_key=True)
    ProductName = Column(String(20))
    ProductDesc = Column(String(50))
    CreationTime = Column(String(20))
    ProductCategory = Column(String(50))


def test():
    db_session = sessionmaker(bind=engine)
    session = db_session()
    user = session.query(User).filter(User.Id == 5).all()
    print(user)

========================= query results:[<main.User object at 0x7fd56b265400>]

I want it to return the specific values of all data that meet the filtering conditions. So,what went wrong?

enter image description here

This is the product table mapped above.

yuzimo
  • 91
  • 5
  • 1
    `[]` is a list of `User` instances returned by the query. `` is the default representation for Python object if the class doesn't provide a `__repr__` method. See [here](https://stackoverflow.com/questions/54026174/proper-autogenerate-of-str-implementation-also-for-sqlalchemy-classes/54034962#54034962) and [here](https://stackoverflow.com/questions/32910096/is-there-a-way-to-auto-generate-a-str-implementation-in-python?noredirect=1&lq=1) for examples of `__repr__` methods. – snakecharmerb Sep 22 '21 at 01:57
  • Thank you for your answer. I've solved this problem @snakecharmerb – yuzimo Sep 22 '21 at 02:08

1 Answers1

1
class BaseModel(object):
    __abstract__ = True
def __init__(self):
    self.__mapper__ = None

def __repr__(self):
    fmt = u'[{}]'
    attrs = (
        (k, str(getattr(self, k)).replace(' ', '')) for k in self.__mapper__.columns.keys()
    )
    sattrs = ','.join('{}={!r}'.format(*x) for x in attrs)
    return fmt.format(sattrs)

Base = declarative_base(cls=BaseModel)
yuzimo
  • 91
  • 5
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 24 '21 at 10:41