Hello everyone...

I'd like to know what do you think it's better: Whether using backrefs
or "manually" defining the relationships one by one. Are the backrefs
useful to code less code or do they have other advantages?

I.e.: Let's say I have a User and a UserGroup class with (initially)
the relationships defined by hand:

class User(declarativeBase):
        __tablename__ = "users"

        _id = Column("id", Integer, primary_key=True)
        _email = Column("email", String(60))
        _userName = Column("user_name", String(50), unique=True, nullable=False)
        _password = Column("password", String(64), nullable=False)
        _userGroupId = Column("user_group_id", Integer, 
ForeignKey("user_groups.id"))

        _userGroup = relationship("UserGroup", uselist=False)

class UserGroup(declarativeBase):
        __tablename__ = "user_groups"

        _id = Column("id", Integer, primary_key=True)
        _name = Column("name", String(50))

        _users = relationship("User", order_by=lambda:User.userName,
cascade="all, delete", collection_class=set)


If, instead, I define that _users (in the UserGroup class) as a backref:


class User(declarativeBase):
        __tablename__ = "users"

        _id = Column("id", Integer, primary_key=True)
        _email = Column("email", String(60))
        _userName = Column("user_name", String(50), unique=True, nullable=False)
        _password = Column("password", String(64), nullable=False)
        _userGroupId = Column("user_group_id", Integer, 
ForeignKey("user_groups.id"))


        _userGroup = relationship("UserGroup", uselist=False, backref=backref(
                backref = backref("_users",
                        order_by=lambda:User._userName,
                        cascade="all, delete",
                        collection_class=set
                )
         ))

and, at a certain point I want to create a resetUsers() method in the
UserGroup class (to empty the "_users" set) I have to add the users in
that set to the session first and then reset it:

class UserGroup(declarativeBase):
        # Yadda, yadda yadda

        def resetUsers(self):
                Database.Session().add_all(self._users)
                self._users = set()

That doesn't happen with the UserGroup._users being a relationship on
its own (not a backref). I can just do self._users = set() and it
seems to work fine. The database looks consistent to me, and all that.

I'd like to know if I'm missing something, or if using backrefs is
better for some reason I don't know yet.

Any advice will be deeply appreciated. Thank you in advance.

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to