django 两种创建模型实例的方法
1. 添加一个classmethod
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
@classmethod
def create(cls, title):
book = cls(title=title)
# do something with the book
return book
book = Book.create("Pride and Prejudice")
这里要用到装饰器(Decorator)。装饰器的概念可以看这里:
2. 在object manager里面添加一个自定义方法,然后把他赋给object。
class BookManager(models.Manager):
def create_book(self, title):
book = self.create(title=title)
# do something with the book
return book
class Book(models.Model):
title = models.CharField(max_length=100)
objects = BookManager()
book = Book.objects.create_book("Pride and Prejudice")
第二种用的比较多。装饰器也比较难理解。