Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find sqlalchemy remote side object's class or class name without db queries?

Let's have a classes X and Y and relations between them x2y and y2x. From class_mapper(Class).iterate_properties iterator we can get all class's properties. So x2y and y2x are RelationshipProperty and what I hope to get from is a class or a class name of objects on remote side of relation.

I've already tried to make a solution. I've found x2y.remote_side[0].table.name, made a tables_map which maps a table name to a class and it works fine for one-to-many and one-to-one. If I use it for many-to-many the table name is an association table.

Any hints on how can I get the remote side class?

like image 726
mdob Avatar asked Jul 27 '11 10:07

mdob


People also ask

What does DB Drop_all () do?

You delete everything in the database using the db. drop_all() function to add the tags and post_tag tables safely and to avoid any of the common issues related to adding new tables to a database. Then you create all the tables anew using the db. create_all() function.

What does Create_all do in SQLAlchemy?

Sqlalchemy create_all method is used to create a new table into the database. This method will first check whether the table exists in the database or not if suppose it has found an existing table it will not create any table.

What is DB Create_all ()?

create_all() function to create the tables that are associated with your models. In this case you only have one model, which means that the function call will only create one table in your database: from app import db, Student.

What is CLS in SQLAlchemy?

cls is a single class (rather than a tuple), the constructed base class will inherit its docstring. as_declarative() function sqlalchemy.ext.declarative. as_declarative(**kw) Class decorator for declarative_base() .


2 Answers

X.x2y.property.mapper.class_

relatonshipproperty will eventually get class-level attribute documentation the same as mapper does now.

edit. Here is a test which illustrates the above returning "Y" from "X", and no reflection doesn't create relationships so should have no effect:

from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class X(Base):
    __tablename__ = 'x'
    id = Column(Integer, primary_key=True)
    x2y = relationship("Y")

class Y(Base):
    __tablename__ = 'y'
    id = Column(Integer, primary_key=True)
    x_id = Column(Integer, ForeignKey("x.id"))

assert X.x2y.property.mapper.class_ is Y
like image 178
zzzeek Avatar answered Oct 27 '22 01:10

zzzeek


I've found that a method argument() on relationshipproperty returns remote class.

for prop in class_mapper(X).iterate_properties:
    if isinstance(prop, RelationshipProperty):
        relation = prop
relation.argument()
like image 40
mdob Avatar answered Oct 26 '22 23:10

mdob