Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: get relationships from a db.Model

I need to get a list of a model's properties which are actually relationships (that is, they were created by relationship()).

Say I have a model Foo in a models:

class Thing(db.Model):
    id = db.Column(...)
    bar_id = db.Column(...)
    foo_id = db.Column(...)
    foo = db.relationship('Foo')
    bar = db.relationship('Bar')

Later on, I want to take models.Thing and get a list of relationship-properties, that is ['foo', 'bar'].

Currently I'm checking every attribute indicated by dir(models.Thing) that happens to be of type sqlalchemy.orm.attributes.InstrumentedAttribute for the class of its property attribute — which can be either a ColumnProperty or RelationshipProperty. This does the job but I was wondering if there's another way.

I could probably just find all attributes ending in _id and derive the relationship name, but this could break for some cases.

How about setting a __relationships__ = ['foo', 'bar']?

Or is there something built into SQLAlchemy to help me out?

like image 873
maligree Avatar asked Jan 18 '14 16:01

maligree


People also ask

What is DB relationship SQLAlchemy?

The relationship function is a part of Relationship API of SQLAlchemy ORM package. It provides a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship.

What is Backref in SQLAlchemy?

In Flask-SQLAlchemy, the backref parameter in relationship method allows you to declare a new property under a specified class as seen in the example in their docs: class Person(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) addresses = db.relationship('Address', backref='person ...

What is DB 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.

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.


2 Answers

There is indeed - take a look at sqlalchemy.inspection.inspect. Calling inspect on a mapped class (for example, your Thing class) will return a Mapper, which has a relationships attribute that is dict like:

from sqlalchemy.inspection import inspect

thing_relations = inspect(Thing).relationships.items()
like image 143
Sean Vieira Avatar answered Oct 16 '22 13:10

Sean Vieira


Instead of using inspect you can also use

model.__mapper__.relationships

like image 30
Pooja Avatar answered Oct 16 '22 14:10

Pooja