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

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

https://docs.djangoproject.com/en/1.8/ref/models/instances/

相关文章:

  • 2021-12-25
  • 2022-12-23
  • 2021-11-27
  • 2021-09-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-16
  • 2021-08-14
  • 2022-12-23
  • 2021-09-15
  • 2022-12-23
  • 2021-08-18
  • 2022-12-23
相关资源
相似解决方案