且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

编写要在 Django 模型中使用的 __init__ 函数

更新时间:2021-07-12 09:51:56

依赖 Django 的内置功能并传递命名参数将是最简单的方法.

Relying on Django's built-in functionality and passing named parameters would be the simplest way to go.

p = User(name="Fred", email="fred@example.com")

但是如果您打算保存一些按键,我建议您向类中添加一个静态方便的方法,而不是弄乱初始化程序.

But if you're set on saving some keystrokes, I'd suggest adding a static convenience method to the class instead of messing with the initializer.

# In User class declaration
@classmethod
def create(cls, name, email):
  return cls(name=name, email=email)

# Use it
p = User.create("Fred", "fred@example.com")