0

I'm currently following Hacked Existence's Django tutorial a bit. I'm having trouble understanding the Django signals involved

    def create_User_callback(sender, instance, **kwargs):                   
        a, b = User.objects.get_or_create(user = instance)

    post_save.connect(create_User_callback, User)

I'm not quite sure the logic behind

     post_save.connect(create_User_callback, User)
4

1 回答 1

2

In order for a signal handler to work, you need to bind it to a signal. That is done using the signal's connect method. In your case, the signal is post_save.

connect is called with the name of the method and the model for which the method will be called. All models will emit post_save, so when you add User as the second argument to connect, it "filters" the signals so only the post_save signal that is emitted by the User model will trigger your method.

Think of it like tuning a radio to listen on a frequency.

Having said all that, this actual code seems a bit pointless. You are creating an object (or fetching one if it exists) of the same class that is emitting the signal; after any object has been saved.

于 2013-08-24T05:40:27.250 回答