-
Hi! I'm working with SQLAlchemy models where some fields are relationships or foreign keys, and I'm using Polyfactory’s I'm wondering if it's possible to define
For example, in a Right now, if some foreign key Thank you for your help, and any examples or guidance would be greatly appreciated! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Hi @MetaHG , Currently Would the example here work for your use case? This doesn't have the upsert behaviour but may work if fine insert each time |
Beta Was this translation helpful? Give feedback.
-
Hi @adhtruong, Sorry for the delay in my response, thank you for replying so quickly! My question is not exactly related to persistence actually. I realize I might have been a bit too broad in my initial question as it initially stemmed from an example I encountered where I found some limitations with the library. My use case is related to database and migration testing. Let's take an example: from __future__ import annotations
from polyfactory.decorators import post_generated
from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory
from sqlalchemy import ForeignKey, Integer, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
class Base(DeclarativeBase):
pass
# Models
class Cake(Base):
__tablename__ = "cake"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
# Relations
menus: Mapped[list[Menu]] = relationship(back_populates="cake")
class IceCream(Base):
__tablename__ = "ice_cream"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
# Relations
menus: Mapped[list[Menu]] = relationship(back_populates="ice_cream")
class Menu(Base):
__tablename__ = "menu"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
# Foreign keys
cake_id: Mapped[int] = mapped_column(ForeignKey("cake.id"))
ice_cream_id: Mapped[int] = mapped_column(ForeignKey("ice_cream.id"))
# Relations
cake: Mapped[Cake] = relationship(back_populates="menu")
ice_cream: Mapped[IceCream] = relationship(back_populates="menu")
# Factories
class CakeFactory(SQLAlchemyFactory[Cake]):
__model__ = Cake
__set_relationships__ = False
__set_primary_key__ = False
id = None
class IceCreamFactory(SQLAlchemyFactory[IceCream]):
__model__ = IceCream
__set_relationships__ = False
__set_primary_key__ = False
id = None
class MenuFactory(SQLAlchemyFactory[Menu]):
__model__ = Menu
__set_relationships__ = True
__set_primary_key__ = False
cake_id = 1
cake = None
ice_cream_id = None
ice_cream = IceCreamFactory I have a case where I know that some
In a sense, I believe that the flag |
Beta Was this translation helpful? Give feedback.
-
I think this should work if set Does this work? |
Beta Was this translation helpful? Give feedback.
I think this should work if set
cake = Ignore()
onMenuFactory
. Currently it is being set to a value which gives this behaviour butIgnore
omits this value entirely.Does this work?