Simple SQLAlchemy Generic Relationship Example

I know that similar questions have been asked, however I'm really trying to understand how generic fields are generated in SQLAlchemy.

I have a class / permissions table that I want to contain a field that can apply to any type of model.

I looked through examples and this blog post http://techspot.zzzeek.org/2007/05/29/polymorphic-associations-with-sqlalchemy/

Is it possible to have a common relationship without a separate table? Just saving object_type and id? Something like that:

class Permission(AbstractBase): user = relationship("User", backref=backref('permissions')) permission_type = column(String()) object = #The object the permission applies to, could be any type. 

I think just a very simple example would be appreciated!

It’s also worth noting that I come from the background of Django!

thanks

+6
source share
2 answers

Someone else asked the same question about a day later, I pointed out three examples that we have for this kind of thing, but I also wrote a new example that will do (basically) the same thing that Django does (minus this weird "contenttypes"): sqlalchemy shared foreign key (e.g. in django ORM)

+1
source

You can also use generic_relationship from the sqlalchemy-utils package.

Here is an example for their documentation ;

 from sqlalchemy_utils import generic_relationship class User(Base): __tablename__ = 'user' id = sa.Column(sa.Integer, primary_key=True) class Customer(Base): __tablename__ = 'customer' id = sa.Column(sa.Integer, primary_key=True) class Event(Base): __tablename__ = 'event' id = sa.Column(sa.Integer, primary_key=True) object_type = sa.Column(sa.Unicode(255)) object_id = sa.Column(sa.Integer) object = generic_relationship(object_type, object_id) 
+5
source

Source: https://habr.com/ru/post/949612/


All Articles