The Xelnor git link shows the best answer so far, but requires changes to the sqlalchemy model. Here is a finished working copy of my post using the Xelnor solution:
# coding=utf-8 from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' db = SQLAlchemy(app)
SQLAlchemy Table Models
class User(db.Model): """ A SQLAlchemy simple model class who represents a user with a ForeignKey Constraint""" __tablename__ = 'user' id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.Unicode(20)) group_id = db.Column(db.Integer, db.ForeignKey('group.id'), nullable=False)
The "db.relationship" of the group is what makes the SubFactory call work. UserFactory passes the group to the user model that is configured with this relationship ().
group = db.relationship('Group', backref=db.backref('groups', lazy='dynamic')) def __init__(self, name, group): self.name = name self.group = group def __repr__(self): return '<Group for %r: %s>' % (self.group, self.name) class Group(db.Model): """ A SQLAlchemy simple model class who represents a user """ __tablename__ = 'group' id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(), nullable=False) def __init__(self, name): self.name = name def __repr__(self): return '<Group %r>' % self.name
Create SQL Tables
db.create_all()
Factory -Boy Custom & Group Factories
from factory import alchemy, Sequence, SubFactory, fuzzy class BaseFactory(alchemy.SQLAlchemyModelFactory): class Meta(object): abstract = True sqlalchemy_session = db.session class GroupFactory(BaseFactory): class Meta(object): model = Group sqlalchemy_session = db.session
Factory tests
source share