search

Home  >  Q&A  >  body text

python - 如何理解django类里的方法

class AccountAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.security = get_random_code(10)
        obj.password = get_password(obj.password, obj.security)
        obj.save()
        Token.objects.create(user=obj)

admin.site.register(Account, AccountAdmin)

save_model()方法里这么多参数用来干什么,还是默认的?
看了下调用,根本就没有传入这么多值嘛。

PHP中文网PHP中文网2812 days ago214

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-17 17:47:32

    I just searched the source code, where save_model is called, all with these parameters,
    For example, Example 1 and Example 2

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 17:47:32

    This method is called when the model is saved, so what is the purpose of this design?

    The answer is: You can easily perform some operations before or after saving. For example, in the code you posted, a new Token is created after saving 设置了security
    保存. The business logic is easy to implement.
    obj is the saved object, form is a ModelForm instance, change is a bool value, indicating whether the obj has been changed. If there is no change, the save method may not be called.

    I have to say that this function is designed to be quite reasonable and convenient.

    reply
    0
  • Cancelreply