Customize using the model manager class

  • First, we need to understand what objects are often used in the end is?
  1. Each model class objects have a default property, which is destined generated by django, we put objects called Model Manager.

 

  • Self-defined application scenarios manager class:
  1. Changing the query result set, packages or the like CRUD
  2. Model Manager conventional method needs to be rewritten

Note: After you customize the model manager class, django does not automatically generate objects and then help us Manager.

Code demonstrates:

class BookInfoManager(models.Manager):
    '''自定义了一个模型管理器类'''

    def all(self):
        '''重写all方法,只返回没有删除的图书'''
        # # 1.调用父类的all,获取所有数据
        # books = super(BookInfoManager, self).all()  # 返回的是queryset
        # # 2.对数据进行过滤
        # books = books.filter(is_delete=False)
        # # 3.返回books
        # return books

        # 简写
        return super().all().filter(is_delete=False)

    def create_books(self, title, pub_date, comment):
        '''封装额外的方法,方便调用'''
        new_book = BookInfo()
        new_book.title = title
        new_book.pub_date = pub_date
        new_book.comment = comment
        new_book.save()
        return new_book


class BookInfo(models.Model):
    title = models.CharField(max_length=20)
    pub_date = models.DateField()
    read = models.IntegerField(default=0)
    comment = models.CharField(max_length=200)
    is_delete = models.BooleanField(default=False)  

    # 自定义管理器类的对象
    objects = BookInfoManager() 

Note: Custom Model Manager class code on the top of the model class, otherwise it will error.

 

  • python manage.py shell into the shell terminal:
>>> from booktest1.models import BookInfo
>>> BookInfo.objects.create_books('test', '2019-6-5', '这个方法真棒')
<BookInfo: BookInfo object>
>>> BookInfo.objects.create_books('封装额外的方法', '2019-6-5', '这个方法真棒')
<BookInfo: BookInfo object>

 

  • Above have been completed since the two application-defined model manager class, but in reality, the name change model class, when do we need to re-package the function to change the name of the model class, then how to do it?

In fact, every model has a manager object model, and its role is to get the model class self resides.

>>> BookInfo.objects.model
<class 'booktest1.models.BookInfo'>
  • This time can be optimized so that the code portion of the function package
def create_book(self, title, pub_date, comment):
        '''封装额外的方法,方便调用'''
        # new_book = BookInfo()
        # 获取self所在的模型类
        new_book = self.model()
        new_book.title = title
        new_book.pub_date = pub_date
        new_book.comment = comment
        new_book.save()
        return new_book

No matter which model class name resolved after how they change, encapsulation methods do not have to modify this one.

Guess you like

Origin blog.csdn.net/wenpy/article/details/90899292