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)。装饰器的概念可以看这里:

http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000

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")

第二种用的比较多。装饰器也比较难理解。

3. 见官网 https://docs.djangoproject.com/en/1.8/ref/models/instances/

原文地址:https://www.cnblogs.com/gqdw/p/4908203.html