我用pytest和Factory Boy测试我的SQLAlchemy模型,但我发现他们的文档在关系方面缺乏。我已经设置了架构,因此有些用户可以属于多个组(组可以容纳多个用户),并且他们可以拥有多个令牌,但令牌只属于一个用户:
_user_groups_table = Table(
'user_groups', Base.metadata,
Column('user_id', INTEGER(unsigned=True), ForeignKey('user.id')),
Column('group_id', INTEGER(unsigned=True), ForeignKey('user_group.id'))
)
class UserGroup(Base):
__tablename__ = 'user_group'
id = Column(INTEGER(unsigned=True), Sequence('user_group_id_seq'), primary_key=True, autoincrement=True)
name = Column(String(255), unique=True, nullable=False)
class User(Base):
__tablename__ = 'user'
id = Column(INTEGER(unsigned=True), Sequence('user_id_seq'), primary_key=True, autoincrement=True)
name = Column(String(255), unique=True, nullable=False)
groups = relationship('UserGroup', secondary=_user_groups_table)
auth_tokens = relationship('Token', cascade='delete')
class Token(Base):
__tablename__ = 'token'
id = Column(INTEGER(unsigned=True), Sequence('token_id_seq'), primary_key=True, autoincrement=True)
user_id = Column(INTEGER(unsigned=True), ForeignKey('user.id'), nullable=False)
value = Column(String(511), unique=True, nullable=False)
我一直在尝试不同的东西,包括添加群组的@ factory.post_generation方法。标记到用户实例,但当我将用户放入夹具并在我的测试函数中使用它时,这些字段永远不会出现。您对如何使用Factory Boy建模此模式有任何建议吗?
答案 0 :(得分:0)
我正在为sqlalchemy写这篇文章,我不知道工厂男孩。您已经拥有一个表,可以让您在用户和组(UserGroup表)和用户令牌之间建立关系,例如:
id user_id group_id id user_id value
1 5 3 1 5 adb45
2 5 4 2 5 xyz01
3 5 5
4 1 9
5 1 3
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(255), unique=True, nullable=False)
tokens = relationship("Token", backref="user")
class Group(Base):
__tablename__ = "groups"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(255), unique=True, nullable=False)
class UserGroup(Base):
__tablename__ = "usergroups"
id = Column(Integer, primary_key=True, autoincrement=True)
group_id = Column(Integer, ForeignKey("Group.id"))
user_id = Column(Integer, ForeignKey("User.id"))
class Token(Base):
__tablename__ = "tokens"
id = Column(Integer, primary_key=True, autoincrement=True)
value = Column(String(511), unique=True, nullable=False)
user_id = Column(Integer, ForeignKey("User.id"))
并且sqlalchemy文档很好。