Skip to content

Doubt in usage of polyfactory #523

@vickypalani

Description

@vickypalani

Hi, I recently started working on a FastAPI project where I needed to create dummy data for a SQLAlchemy model that has a unique field. This is my code to implement it. 

class AsyncPersistenceHandler(AsyncPersistenceProtocol[T]):
    async def save(self, data: T) -> T:
        async with get_db_context() as session:
            session.add(data)
            await session.commit()

    async def save_many(self, data: List[T]) -> List[T]:
        async with get_db_context() as session:
            session.add_all(data)
            await session.commit()

class BaseFactory(SQLAlchemyFactory):
    """
    Base Factory
    """
    __is_base_factory__ = True
    __async_persistence__ = AsyncPersistenceHandler


class RoleTypeFactory(BaseFactory):
    """
    RoleType Factory
    """
    __model__ = neo_hire_models.RoleType

    id = Ignore()
    name = Faker().name()

When I try to create a batch like this, 

await RoleTypeFactory.create_batch_async(size=5)

I get an issue since the name field uses the same value for all the instances, thus triggering the UniqueConstraint error.
 
 
 This is my SQLAlchemyModel for reference

class RoleType(SoftDeleteMixin, BaseModal):
    __tablename__ = "role_types"

    id = Column(Integer, primary_key=True)
    name = Column(String(255), unique=True, nullable=False)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions