11

我有一个表格 Users 和一个表格 Friends ,它们将用户映射到其他用户,因为每个用户可以有很多朋友。这个关系显然是对称的:如果用户 A 是用户 B 的朋友,那么用户 B 也是用户 A 的朋友,我只存储这个关系一次。Friends 表除了两个用户 ID 之外还有其他字段,因此我必须使用关联对象。

我试图在用户类(它扩展了声明性基础)中以声明式风格定义这种关系,但我似乎无法弄清楚如何做到这一点。我希望能够通过属性朋友访问给定用户的所有朋友,所以说朋友 = bob.friends。

解决这个问题的最佳方法是什么?我尝试了许多不同的设置在这里发布,但由于各种原因,它们都没有工作。

编辑:我最近的尝试是这样的:

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)

    # Relationships
    friends1 = relationship('Friends', primaryjoin=lambda: id==Friends.friend1ID)
    friends2 = relationship('Friends', primaryjoin=lambda: id==Friends.friend2ID)


class Friends(Base):
    __tablename__ = 'friends'
    id = Column(Integer, primary_key=True)
    friend1ID = Column(Integer, ForeignKey('users.id') )
    friend2ID = Column(Integer, ForeignKey('users.id') )
    status = Column(Integer)

    # Relationships
    vriend1 = relationship('Student', primaryjoin=student2ID==Student.id)
    vriend2 = relationship('Student', primaryjoin=student1ID==Student.id)

但是,这会导致以下错误:

InvalidRequestError: Table 'users' is already defined for this MetaData instance.  Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

我必须承认,在这一点上,由于许多失败的尝试,我完全糊涂了,并且可能在上面犯了不止一个愚蠢的错误。

4

3 回答 3

20

该特定异常是由多次描述表引起的,或者通过重复定义类映射(例如,在交互式解释器中,或者在可以多次调用的函数中),或者通过将声明性样式类映射与表混合反射。前一种情况,消除重复调用;如果您以交互方式执行它,请启动一个新的解释器,或者消除额外的函数调用(可能对单例/borg 对象很有用)。

在后一种情况下,只需按照异常所说的去做,__table_args__ = {'extend_existing': True}在类定义中添加一个额外的类变量。仅当您确实确定表被正确描述了两次时才执行此操作,就像表反射一样。

于 2011-09-05T20:04:56.293 回答
2

我在使用 Flask-SQLAlchemy 时遇到了这个错误,但其他解决方案不起作用。

该错误仅发生在我们的生产服务器上,而在我的计算机和测试服务器上一切正常。

我有一个“模型”类,我的所有其他数据库类都继承自:

class Model(db.Model):

    id = db.Column(db.Integer, primary_key=True)

出于某种原因,ORM 为从此类继承的类赋予了与此类相同的名。也就是说,对于它试图为它创建一个称为表“模型”的表的每个类。

解决方案是使用“ tablename ”类变量显式命名子表:

class Client(Model):

    __tablename__ = "client"

    email = db.Column(db.String)
    name = db.Column(db.String)
    address = db.Column(db.String)
    postcode = db.Column(db.String)
于 2016-02-25T09:45:31.150 回答
1

正如评论中提到的,我更喜欢扩展模型,其中Friendship它本身就是一个实体,朋友之间的链接是独立的实体。通过这种方式,人们可以存储对称和不对称的属性(就像一个人对另一个人的看法一样)。因此,下面的模型应该向您展示我的意思:

...
class User(Base):
    __tablename__ =  "user"

    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False)

    # relationships
    friends = relationship('UserFriend', backref='user',
            # ensure that deletes are propagated
            cascade='save-update, merge, delete',
    )

class Friendship(Base):
    __tablename__ =  "friendship"

    id = Column(Integer, primary_key=True)
    # additional info symmetrical (common for both sides)
    status = Column(String(255), nullable=False)
    # @note: also could store a link to a Friend who requested a friendship

    # relationships
    parties = relationship('UserFriend', 
            back_populates='friendship',
            # ensure that deletes are propagated both ways
            cascade='save-update, merge, delete',
        )

class UserFriend(Base):
    __tablename__ =  "user_friend"

    id = Column(Integer, primary_key=True)
    friendship_id = Column(Integer, ForeignKey(Friendship.id), nullable=False)
    user_id = Column(Integer, ForeignKey(User.id), nullable=False)
    # additional info assymmetrical (different for each side)
    comment = Column(String(255), nullable=False)
    # @note: one could also add 1-N relationship where one user might store
    # many different notes and comments for another user (a friend)
    # ...

    # relationships
    friendship = relationship(Friendship,
            back_populates='parties',
            # ensure that deletes are propagated both ways
            cascade='save-update, merge, delete',
        )

    @property
    def other_party(self):
        return (self.friendship.parties[0] 
                if self.friendship.parties[0] != self else
                self.friendship.parties[1]
                )

    def add_friend(self, other_user, status, comment1, comment2):
        add_friendship(status, self, comment1, other_user, comment2)

# helper method to add a friendship
def add_friendship(status, usr1, comment1, usr2, comment2):
    """ Adds new link to a session.  """
    pl = Friendship(status=status)
    pl.parties.append(UserFriend(user=usr1, comment=comment1))
    pl.parties.append(UserFriend(user=usr2, comment=comment2))
    return pl

通过这种方式,添加友谊非常容易。更新它的任何属性也是如此
。您可以创建更多的辅助方法,例如. 使用上面的配置也删除a将确保双方都被删除。选择所有朋友非常简单:add_friend
cascadeUser or Friendship or UserFriend
print user.friends

此解决方案的真正问题是确保UserFriend每个Friendship. 同样,当从代码中操作对象时,这应该不是问题,但是如果有人直接在 SQL 端导入/操作某些数据,数据库可能会不一致。

于 2011-09-06T08:51:12.770 回答