Sqlalchemy backref without a name, but a cascade

We have a custom class for people registered in the system. And we have loading classes (and add more plugins) owned by the user. Therefore, if the user is deleted, his things should be deleted. So here is what we are doing now:

class User(Base): id = Column(Integer, primary_key=True) class Thing(Base): user_id = Column(Integer, ForeignKey(User.id)) user = relationship( User, backref=backref("list_of_things", cascade="all, delete-orphan")) 

It works.

Suppose we never use User.list_of_things : is there a way to leave this? But still get cascading backref behavior? If we ever need User.list_of_things , we can add that, of course. But before that it would be nice to leave it.

You could say, "Well, just enter a name and don't care." This is what we do. Two things:

  • We will need to define a naming convention only for this thing so that the names from the plugins do not conflict with the User class with other plugins and / or our main attributes.
  • It will be easier to read / write.

A small update. An untested solution to our problem would be line-wise mixing, but would not answer the question about backrefs without names:

 class OwnedbyUserMixin(object): @declared_attr def user_id(cls): return Column(Integer, ForeignKey(User.id), nullable=False) @declared_attr def user(cls): return relationship( User, backref=backref("list_of_" + cls.__tablename__, cascade="all, delete-orphan")) 
+6
source share

All Articles