litestar-org / polyfactory

Simple and powerful factories for mock data generation
https://polyfactory.litestar.dev/
MIT License
988 stars 78 forks source link

Doubt in usage of polyfactory #523

Closed vickypalani closed 4 months ago

vickypalani commented 4 months ago

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)

 


[!NOTE]
While we are open for sponsoring on GitHub Sponsors and OpenCollective, we also utilize Polar.sh to engage in pledge-based sponsorship.

Check out all issues funded or available for funding on our Polar.sh dashboard

  • If you would like to see an issue prioritized, make a pledge towards it!
  • We receive the pledge once the issue is completed & verified
  • This, along with engagement in the community, helps us know which features are a priority to our users.

Fund with Polar

Alc-Alc commented 4 months ago

Can you try this?

from polyfactory import Use
class RoleTypeFactory(BaseFactory):
    """
    RoleType Factory
    """
    __model__ = neo_hire_models.RoleType

    id = Ignore()
    name = Use(lambda: Faker().name())

I would recommend name = Use(lambda: RoleTypeFactory.__faker__.name()) instead of creating your own faker