question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

save() method called twice when using post_generation

See original GitHub issue

I just realised that my model factory was calling the model save method twice when defining post_generation function. Here is the many-to-many example:

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.User

    name = "John Doe"

    @factory.post_generation
    def groups(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of groups were passed in, use them
            for group in extracted:
                self.groups.add(group)

Calling UserFactory triggers save() on User model twice.

This happens because: 1/ The DjangoModelFactory redefines _after_postgeneration:

    @classmethod
    def _after_postgeneration(cls, obj, create, results=None):
        """Save again the instance if creating and at least one hook ran."""
        if create and results:
            # Some post-generation hooks ran, and may have modified us.
            obj.save()

2/ This results comes from the call to our post_generation function, which with previous User example returns {'groups': None}

Which use case has led to this post-generation saving? If some data had to be saved in a custom post_generation function, nothing is preventing to explicitly call save on obj.

Do I have missed something? Should I override this method if I don’t want to get this double save() on my model, or there is a better way?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:1
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
rbarroiscommented, Aug 6, 2016

This is useful for declarations such as:

class UserFactory(factory.Factory):
    class Meta:
        model = User

    username = factory.Faker('username')
    password = factory.PostGenerationMethodCall('set_password', 'Password123')

In such cases, we want to have the factory be saved again after the call to set_password.

What kinds of problems are caused by this double save()?

1reaction
gruttscommented, Aug 4, 2016

I had this problem as well, spotted it when one of my tests was behaving unexpectedly. I overrode _after_postgeneration to do nothing

Read more comments on GitHub >

github_iconTop Results From Across the Web

Django save method called twice? - python - Stack Overflow
First you will create save 'instance', do what you have to do, and then call the right save() method. Share.
Read more >
Common recipes — Factory Boy stable documentation
When any RelatedFactory or post_generation attribute is defined on the DjangoModelFactory subclass, a second save() is performed after the call to _create() ....
Read more >
Save post action is called twice - WordPress Stack Exchange
I noticed there was a 302 redirect in my network tab while saving. Save_post was being triggered twice, once from. Inside my call,...
Read more >
[Answered]-Django save method called twice?
Your save method does not have proper indentation. I assume this was an error in cut and paste. With in that method. if...
Read more >
VuGen(Virtual User Generator) Script Example in LoadRunner
using the pause button. Please note, as long as the recording remains paused, all events being fired by the application will be disregarded....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found