创建模型对象的两种方式
使用关键字构造模型对象非常麻烦,一下介绍两种创建对象的方式。
方式一:在模型类中增加一个类方法—不推荐使用
class ExampleModel(models.Model):
...
@classmethod
def create(cls, attr1, attr2, ...):
e = ExampleModel()
e.attr1 = attr1
e.attr2 = attr2
...
return e
方式二:在自定义管理器中添加一个方法—推荐使用
class ExampleModelManager(models.Manager):
def create(self, attr1, attr2, ...):
e = ExampleModel() # 使用在方式一中定义的模型类ExampleModel
e.attr1 = attr1
e.attr2 = attr2
...
return e
**Note:**管理器是模型类的属性,用于将对象与数据表映射