def generate_slug(self, depth=0): search_for = utils.slugify(self.name) if depth > 0: search_for = utils.slugify("%s-%d" % (self.name, depth)) result = Taxonomy.query.filter_by(slug=search_for).first() if result is None: return search_for else: return self.generate_slug(depth + 1)
def upgrade(): connection = op.get_bind() op.create_table('authors', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=True), sa.Column('slug', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.add_column('books', sa.Column('author_id', sa.Integer(), sa.ForeignKey('authors.id')) ) books = sa.Table('books', sa.MetaData(), autoload=True, autoload_with=connection) authors = sa.Table('authors', sa.MetaData(), autoload=True, autoload_with=connection) # move authors to the table and relate to books for book in connection.execute(sa.select([books])).fetchall(): author_query = authors.select().where(authors.c.name == book['author']) found_author = connection.execute(author_query).first() if found_author is None: slug = slugify(book['author']) ins = authors.insert().values(name=book['author'], slug=slug) author_id = connection.execute(ins).inserted_primary_key[0] else: author_id = found_author['id'] connection.execute( books.update().where(books.c.id == book['id']).values(author_id=author_id) ) op.drop_column('books', 'author')