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

Related factory overriding #1102

Open
ihorm5 opened this issue Nov 6, 2024 · 0 comments
Open

Related factory overriding #1102

ihorm5 opened this issue Nov 6, 2024 · 0 comments

Comments

@ihorm5
Copy link

ihorm5 commented Nov 6, 2024

I recently updated my project from Django 3.2 to Django 5.0. One particular issue I encountered was related to factory_boy. Here’s what happened:

The Problem

I had the following factory definition:

class MemberFactory(BaseFactory):
    class Meta:
        model = User
        django_get_or_create = ('email',)

    gov_id_verification = factory.RelatedFactory('api.tests.factories.GovernmentIDVerificationFactory', 'user')

In previous versions, I could easily override gov_id_verification in a subclassed factory like this:

class MemberFactory2(MemberFactory):
    gov_id_verification = None

But during the update, this started raising an error: ValueError: The following fields do not exist in this model: gov_id_verification.

The Solution I Used

To resolve this, I ended up using a post_generation method to control whether the related factory should be created or not. Here’s the solution I used:

@factory.post_generation
def gov_id_verification(self, create, extracted, **kwargs):
    # Override gov_id_verification to skip its creation in MemberFactory2
    if create and extracted is not False:
        # Create a new government ID verification only if explicitly requested
        GovernmentIDVerificationFactory(user=self, **(extracted or {}))

Question

Is there an easier way to handle such cases where I want to make related factories optional in a clean and straightforward manner?

I’d appreciate any suggestions or tips on simplifying this process.

@ihorm5 ihorm5 closed this as completed Nov 6, 2024
@ihorm5 ihorm5 changed the title Related factory can't pass nested parameters Related factory overriding Nov 6, 2024
@ihorm5 ihorm5 reopened this Nov 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant