通过SqlAlchemy中的关联对象实现多对多,自引用,非对称关系(推特模型)

时间:2015-01-06 02:15:52

标签: python sqlalchemy many-to-many relationship

如何在SqlAlchemy中最好地实现多对多,自我引用,非对称关系(想想Twitter)?我想使用一个关联对象(让我们称这个类为“Follow”),这样我就可以拥有与这种关系相关的其他属性。

我见过很多使用关联表的例子,但没有像我上面描述的那样。这是我到目前为止所做的:

class UserProfile(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    full_name = Column(Unicode(80))
    gender = Column(Enum(u'M',u'F','D', name='gender'), nullable=False)
    description = Column(Unicode(280))
    followed = relationship(Follow, backref="followers") 

class Follow(Base):
    __tablename__ = 'follow'

    follower_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
    followee_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
    status = Column(Enum(u'A',u'B', name=u'status'), default=u'A')
    created = Column(DateTime, default=func.now())
    followee = relationship(UserProfile, backref="follower")

思想?

1 个答案:

答案 0 :(得分:4)

here已经几乎回答了这个问题。这里通过使用裸链接表创建多对多的优点来改进。

我在SQL方面并不擅长,而且在SqlAlchemy中也没有好处,但由于我已经考虑了这个问题一段时间了,我试图找到一个既有优势的解决方案:具有附加属性的关联对象和 direct 与裸链接表(无法为关联提供对象)之间的关联。受到op的其他建议的刺激,以下内容对我来说似乎很安静:

#!/usr/bin/env python3
# coding: utf-8

import sqlalchemy as sqAl
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.associationproxy import association_proxy

engine = sqAl.create_engine('sqlite:///m2m-w-a2.sqlite') #, echo=True)
metadata = sqAl.schema.MetaData(bind=engine)

Base = declarative_base(metadata)

class UserProfile(Base):
  __tablename__ = 'user'

  id            = sqAl.Column(sqAl.Integer, primary_key=True)
  full_name     = sqAl.Column(sqAl.Unicode(80))
  gender        = sqAl.Column(sqAl.Enum('M','F','D', name='gender'), default='D', nullable=False)
  description   = sqAl.Column(sqAl.Unicode(280))
  following     = association_proxy('followeds', 'followee')
  followed_by   = association_proxy('followers', 'follower')

  def follow(self, user, **kwargs):
    Follow(follower=self, followee=user, **kwargs)

  def __repr__(self):
    return 'UserProfile({})'.format(self.full_name)

class Follow(Base):
  __tablename__ = 'follow'

  followee_id   = sqAl.Column(sqAl.Integer, sqAl.ForeignKey('user.id'), primary_key=True)
  follower_id   = sqAl.Column(sqAl.Integer, sqAl.ForeignKey('user.id'), primary_key=True)
  status        = sqAl.Column(sqAl.Enum('A','B', name=u'status'), default=u'A')
  created       = sqAl.Column(sqAl.DateTime, default=sqAl.func.now())
  followee      = relationship(UserProfile, foreign_keys=followee_id, backref='followers')
  follower      = relationship(UserProfile, foreign_keys=follower_id, backref='followeds')

  def __init__(self, followee=None, follower=None, **kwargs):
    """necessary for creation by append()ing to the association proxy 'following'"""
    self.followee = followee
    self.follower = follower
    for kw,arg in kwargs.items():
      setattr(self, kw, arg)

Base.metadata.create_all(engine, checkfirst=True)
session = sessionmaker(bind=engine)()

def create_sample_data(sess):
  import random
  usernames, fstates, genders = ['User {}'.format(n) for n in range(4)], ('A', 'B'), ('M','F','D')
  profs = []
  for u in usernames:
    user = UserProfile(full_name=u, gender=random.choice(genders))
    profs.append(user)
    sess.add(user)

  for u in [profs[0], profs[3]]:
    for fu in profs:
      if u != fu:
        u.follow(fu, status=random.choice(fstates))

  profs[1].following.append(profs[3]) # doesn't work with followed_by

  sess.commit()

# uncomment the next line and run script once to create some sample data
# create_sample_data(session)

profs = session.query(UserProfile).all()

print(       '{} follows {}: {}'.format(profs[0], profs[3], profs[3] in profs[0].following))
print('{} is followed by {}: {}'.format(profs[0], profs[1], profs[1] in profs[0].followed_by))

for p in profs:
  print("User: {0}, following: {1}".format(
    p.full_name,  ", ".join([f.full_name for f in p.following])))
  for f in p.followeds:
    print(" " * 25 + "{0} follow.status: '{1}'"
          .format(f.followee.full_name, f.status))
  print("            followed_by: {1}".format(
    p.full_name,  ", ".join([f.full_name for f in p.followed_by])))
  for f in p.followers:
    print(" " * 25 + "{0} follow.status: '{1}'"
          .format(f.follower.full_name, f.status))

Association Object定义两个关系似乎是不可或缺的。 association_proxy方法似乎不适合自我指涉关系。 Follow构造函数的参数oder对我来说似乎不合逻辑,但只是这样工作(这解释为here)。

在第117页的Rick Copeland - Essential Sqlalchemy一书中,您可以找到以下有关secondary - relationship()参数的说明:

  

请注意,如果您使用SQLAlchemy执行M:N的能力   关系,连接表应用于连接两者   桌子在一起,不存储辅助属性。如果你需要   使用中间连接表来存储其他属性   关系,你应该使用两个1:N关系。

很抱歉,这有点冗长,但我喜欢可以直接复制,粘贴和执行的代码。这适用于Python 3.4和SqlAlchemy 0.9,但也可能与其他版本一起使用。