1. 程式人生 > >Django入門學習(7)——自定義管理器和模型類的建立方法

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