Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy Generic Relationship simple example

I know similar questions have been asked, however I am really struggling to understand how generic fields are implemented in SQLAlchemy.

I have a Permissions class/table which I want to contain a field which can relate to any model type.

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

Is it possible to have a generic relation without a separate table? Just by storing the object_type and id? Something along these lines:

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 guess just a really simple example would be appreciated!

Also, it's worth noting I am coming from a Django background!

Thanks

like image 267
Charlie Avatar asked Jul 16 '13 22:07

Charlie


People also ask

What is a generic relationship?

Generic relationships are abstraction patterns used for structuring information across application domains. They play a central role in information modeling.

How do I create a many to many relationship in SQLAlchemy?

Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table's primary key.

How do you query a one to many relationship in flask?

The comments class attribute defines a One-to-Many relationship between the Post model and the Comment model. You use the db. relationship() method, passing it the name of the comments model ( Comment in this case). You use the backref parameter to add a back reference that behaves like a column to the Comment model.


2 Answers

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

Here's 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)
like image 83
smilly92 Avatar answered Sep 17 '22 13:09

smilly92


Someone else asked the identical question about a day later, I pointed to the three examples we have for this kind of thing but also I wrote a new example that will do (mostly) the same thing Django does (minus that weird "contenttypes" table): sqlalchemy generic foreign key (like in django ORM)

like image 24
zzzeek Avatar answered Sep 20 '22 13:09

zzzeek