Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected behavior when providing foreign key id instead of relationship when dealing with ORM factory #1105

Open
paulshih85 opened this issue Nov 15, 2024 · 1 comment

Comments

@paulshih85
Copy link

Description

I've created an ORM factory that generates a must-have relationship using SubFactory by default.
I expected it'll be replaced if I provide either the foreign key ID or the related object, but it didn't.

To Reproduce

There's a working example below.

Model / Factory code
# Model
class User(Base):
    __tablename__ = 'user'

    address_id = Column('address_id', Integer, ForeignKey('address.id', ondelete='CASCADE'), index=True, nullable=False)
    address = relationship('Address', cascade='all, delete')

# Factory
class AddressFactory(factory.Factory):

    class Meta:
        model = Address


class UserFactory(factory.Factory):

    class Meta:
        model = User

    address = factory.SubFactory(AddressFactory)
The issue
address = AddressFactory.build()
session.add(address)
session.commit()

user = UserFactory.build(address_id=address_id)

I expected that the created user's address would be the address I provided, but it seems that it is covered by the address created by the subfactory.

@rbarrois
Copy link
Member

Indeed, factory_boy does not inspect your model structure; nor is it aware of the magic performed by the ORM library.

In its view, the address and address_id fields are unrelated, and live separate lives.

If you pass in (address_id=address_id, address=None), the second part will prevent the subfactory to be built.
You'll have to check whether your ORM behaves as you'd expect when calling User(address=None, address_id=42)

If that works, I'll be glad to add that suggestion to the documentation's common recipes section!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants