0

I had a problem with post_save being called twice and I spent a lot of time figuring out the imports as had been mentioned. I confirmed that the import is happening only once and there is no question of multiple registrations. Besides I'm using a unique dispatch_uid in the signal registration which as per the documentation should have solved the problem. It did not. I looked more carefully and saw that the signal handler gets called on .create() as well as .save(). Why for create?

The only way I could get it to work is by relying on the hack below inside my signal handler

created = False

    #Workaround to signal being emitted twice on create and save
    if 'created' in kwargs:
        if kwargs['created']:
            created=True

    #If signal is from object creation, return
    if created:
        return

This is a follow up to question Django post save signal getting called twice despite uid

Community
  • 1
  • 1
Pratik Mandrekar
  • 9,362
  • 4
  • 45
  • 65
  • Presumably you want a better answer than "because creation is instantiation plus saving"? – Ignacio Vazquez-Abrams Aug 19 '12 at 18:44
  • @IgnacioVazquez-Abrams Is MyClass.objects.create(...) different from just initializing MyClass(...) in general or specifically to signals? I have been thinking both ways of creation to be the same and wondering why it doesn't obey `Note that instantiating a model in no way touches your database; for that, you need to save().` – Pratik Mandrekar Aug 19 '12 at 19:23

1 Answers1

1

Because "creation" is instantiation plus saving.

create(**kwargs)

A convenience method for creating an object and saving it all in one step. Thus:

p = Person.objects.create(first_name="Bruce", last_name="Springsteen")

and:

p = Person(first_name="Bruce", last_name="Springsteen")
p.save(force_insert=True)

are equivalent.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358