1

他の 2 つの関係を効果的に結合した自己参照型の多対多の関係を実装するにはどうすればよいですか?

この関係は、ネットワーク内のユーザーと他のユーザーの間に存在するすべての FacebookFriendship モデルを返す必要があります。ユーザーは、別の既存のユーザーを指す FacebookFriendship を持っている場合がありますが、FB API の停止、プライバシー制御などにより、既存のユーザーからこのユーザーへのミラー FBFriendship が存在しない場合があります。

# This class is necessary for python-social-auth
# A UserSocialAuth model only exists for users who are in the network
class UserSocialAuth(_AppSession, Base, SQLAlchemyUserMixin):
    """Social Auth association model"""
    __tablename__ = 'social_auth_usersocialauth'
    __table_args__ = (UniqueConstraint('provider', 'uid'),)
    id = Column(Integer, primary_key=True)
    provider = Column(String(32))
    uid = Column(String(UID_LENGTH))
    extra_data = Column(JSONType())
    user_id = Column(
        Integer, ForeignKey(User.id), nullable=False, index=True)
    user = relationship(
        User,
        backref=backref('social_auth', lazy='dynamic')
    )

この関係は、このユーザーから既存のユーザーを指す FacebookFriendship モデルを見つけます。

    facebook_friendships = relationship(
        FacebookFriendship,
        primaryjoin=and_(
            user_id == FacebookFriendship.user_id,
            provider == 'facebook'
        ),
        secondary=FacebookFriendship.__table__,
        secondaryjoin=uid == FacebookFriendship.fb_uid_friend,
        foreign_keys=[provider, user_id, uid],
        viewonly=True,
        uselist=True,
        lazy='dynamic',
    )

この関係は、このユーザーを指す FacebookFriendship モデルを見つけます。

    other_facebook_friendships = relationship(
        FacebookFriendship,
        primaryjoin=and_(
            uid == FacebookFriendship.fb_uid_friend,
            provider == 'facebook'
        ),
        foreign_keys=[provider, uid],
        viewonly=True,
        uselist=True,
        lazy='dynamic',
    )

Hybrid_property デコレーターを使用してユニオン クエリを表現することはできましたが、これにより、少なくとも私が知る限り、any() のようなコンパレーターを使用したり、関連付けプロキシを使用したりできなくなります。

    # Can I rewrite this using relationship()?
    @hybrid_property
    def all_facebook_friendships(self):
        return self.facebook_friendships.union(
            self.other_facebook_friendships).correlate(
            FacebookFriendship)

# FBFriendship models are created for every friend that a user has,
# regardless of whether they're in the network or not.
class FacebookFriendship(Base):
    __tablename__ = u'user_fb_friend'

    user_id = Column(Integer, sa.ForeignKey(User.id), primary_key=True)

    user = relationship(
        User, backref=backref('facebook_friendships', lazy='dynamic'),
        primaryjoin=User.id == user_id)

    fb_uid_friend = Column(sa.String(length=255), primary_key=True)

最後に、他の InstrumentedAttribute と同じようにこの関係をクエリ UserSocialAuth.query.filter(UserSocialAuth.all_facebook_friendships.any()).all() し、 User モデルで association_proxy を定義します。

User.all_facebook_friends = association_proxy('all_facebook_friendships', 'user')

この質問が長くなって申し訳ありませんが、私は何日も試行錯誤を繰り返してきました。

関連している:

4

1 に答える 1

1

上でリンクされた zzzeek のソリューションを使用して、relationship() の「2 番目の」引数として select ステートメントを使用して、自己参照型の M2M 関係を作成しました。

friendship_union = select([
    FacebookFriendship.dater_id,
    cast(FacebookFriendship.fb_uid_friend, Integer()).label(
        'fb_uid_friend')
]).union(
    select([
        cast(FacebookFriendship.fb_uid_friend, Integer()),
        FacebookFriendship.dater_id]
    )
).alias()

cls.all_fb_friendships = relationship(
    UserSocialAuth,
    secondary=friendship_union,
    primaryjoin=UserSocialAuth.user_id == friendship_union.c.dater_id,
    secondaryjoin=and_(
        UserSocialAuth.provider == 'facebook',
        cast(UserSocialAuth.uid, Integer() ) == friendship_union.c.fb_uid_friend,
    ),
    viewonly=True
)
于 2014-06-12T23:58:45.287 に答える