Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object is an sqlalchemy model instance

Tags:

sqlalchemy

I want to know how to know, given an object, if it is an instance of an sqlalchemy mapped model.

Normally, I would use isinstance(obj, DeclarativeBase). However, in this scenario, I do not have the DeclarativeBase class used available (since it is in a dependency project).

I would like to know what is the best practice in this case.

class Person(DeclarativeBase):
      __tablename__ = "Persons"

p = Person()

print isinstance(p, DeclarativeBase)
#prints True

#However in my scenario, I do not have the DeclarativeBase available
#since the DeclarativeBase will be constructed in the depending web app
#while my code will act as a library that will be imported into the web app
#what are my alternatives?
like image 219
Ahmed Avatar asked Oct 05 '11 07:10

Ahmed


People also ask

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 a model SQLAlchemy?

SQLAlchemy (source code) is a Python library for accessing persistent data stored in relational databases either through raw SQL or an object-relational mapper.

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.

What does First () do in SQLAlchemy?

first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present). Calling Query. first() results in an execution of the underlying query.


1 Answers

You can use class_mapper() and catch the exception.
Or you could use _is_mapped_class, but ideally you should not as it is not a public method.

from sqlalchemy.orm.util import class_mapper
def _is_sa_mapped(cls):
    try:
        class_mapper(cls)
        return True
    except:
        return False
print _is_sa_mapped(MyClass)

# @note: use this at your own risk as might be removed/renamed in the future
from sqlalchemy.orm.util import _is_mapped_class
print bool(_is_mapped_class(MyClass))
like image 177
van Avatar answered Nov 15 '22 10:11

van



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!