Django入门学习(7)——自定义管理器和模型类的创建方法

自定义管理器的目的1:更改查询集

# -*- coding:utf-8 -*-
from django.db import models


class BookInfoManager(models.Manager):
    def get_queryset(self):
        return super(BookInfoManager,self).get_queryset().filter(isDelete=False)

class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)
    bpub_date = models.DateTimeField(db_column='pub_date')#字段的名字,如果未指定,则用属性名称
    bread = models.IntegerField(default=0)#整数类型
    bcommet = models.IntegerField(null=False)#整数类型,约束:不能为空
    isDelete = models.BooleanField(default=False)
    class Meta:
        db_table = 'bookinfo'
    books1 = models.Manager()
    books2 = BookInfoManager()

自定义管理器的目的2: 模型类创建方法:

class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)
    bpub_date = models.DateTimeField(db_column='pub_date')#字段的名字,如果未指定,则用属性名称
    bread = models.IntegerField(default=0)#整数类型
    bcommet = models.IntegerField(null=False)#整数类型,约束:不能为空
    isDelete = models.BooleanField(default=False)
    class Meta:
        db_table = 'bookinfo'
    books1 = models.Manager()
    books2 = BookInfoManager()
    @classmethod
    def create(cls,btitle,bpub_date):
        b = BookInfo()
        b.btitle = btitle
        b.bpub_date = bpub_date
        b.bread = 0
        b.bcommet = 0
        b.isDelete = False
        return b

在shell中测试:

python manage.py shell
from booktest.models import BookInfo
from datetime import datetime
b = BookInfo.create('Gone with the Wind',datetime(1936,1,1))
b.save()

或者在自定义的管理器中增加一个create对象方法,也能实现同样的效果:(推荐)

class BookInfoManager(models.Manager):
    def get_queryset(self):
        return super(BookInfoManager,self).get_queryset().filter(isDelete=False)
    def create(cls, btitle, bpub_date):
        b = BookInfo()
        b.btitle = btitle
        b.bpub_date = bpub_date
        b.bread = 0
        b.bcommet = 0
        b.isDelete = False
        return b

在shell中测试:

python manage.py shell
from booktest.models import BookInfo
from datetime import datetime
b = BookInfo.books2.create('Gone with the Wind',datetime(1936,1,1))
b.save()

你可能感兴趣的:(Django入门学习(7)——自定义管理器和模型类的创建方法)