Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method of iterating over sqlalchemy model's defined columns?

I've been trying to figure out how to iterate over the list of columns defined in a SQLAlchemy model. I want it for writing some serialization and copy methods to a couple of models. I can't just iterate over the obj.__dict__ since it contains a lot of SA specific items.

Anyone know of a way to just get the id and desc names from the following?

class JobStatus(Base):     __tablename__ = 'jobstatus'      id = Column(Integer, primary_key=True)     desc = Column(Unicode(20)) 

In this small case I could easily create a:

def logme(self):     return {'id': self.id, 'desc': self.desc} 

but I'd prefer something that auto-generates the dict (for larger objects).

like image 338
Rick Avatar asked Mar 29 '10 11:03

Rick


People also ask

How do I get column names in SQLAlchemy?

To access the column names we can use the method keys() on the result. It returns a list of column names. Since, we queried only three columns, we can view the same columns on the output as well.

What is __ repr __ SQLAlchemy?

The __repr__ function is defined by the designer of a type, in order to provide a means for users of the type to represent values of that type unambiguously, with a string.

What is _sa_instance_state in SQLAlchemy?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.


1 Answers

You could use the following function:

def __unicode__(self):     return "[%s(%s)]" % (self.__class__.__name__, ', '.join('%s=%s' % (k, self.__dict__[k]) for k in sorted(self.__dict__) if '_sa_' != k[:4])) 

It will exclude SA magic attributes, but will not exclude the relations. So basically it might load the dependencies, parents, children etc, which is definitely not desirable.

But it is actually much easier because if you inherit from Base, you have a __table__ attribute, so that you can do:

for c in JobStatus.__table__.columns:     print c  for c in JobStatus.__table__.foreign_keys:     print c 

See How to discover table properties from SQLAlchemy mapped object - similar question.

Edit by Mike: Please see functions such as Mapper.c and Mapper.mapped_table. If using 0.8 and higher also see Mapper.attrs and related functions.

Example for Mapper.attrs:

from sqlalchemy import inspect mapper = inspect(JobStatus) for column in mapper.attrs:     print column.key 
like image 145
van Avatar answered Oct 30 '22 11:10

van