python - 如何理解django类里的方法
PHP中文网
PHP中文网 2017-04-17 17:45:32
0
2
186
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中文网

认证高级PHP讲师

reply all(2)
刘奇

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

刘奇

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.
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!