django中对model模型添加方法

如果要在django的模型中添加方法,推荐在模型的自定义管理其中添加方法。

不能使用__init__方法,因为模型继承的父类也有__init__方法。

模型models.py中

关键代码:

class BookInfoManager(models.Manager):
    # 自定义管理器:应用二  扩展方法
    def create_book(self, btitle, bpub_date, bread):
        book = BookInfo()
        book.btitle = btitle
        book.bpub_date = bpub_date
        book.bread = bread
        book.save()
        return book

# 定义图书模型类BookInfo
class BookInfo(models.Model):

    book2 = BookInfoManager()

完整代码:

# coding=utf-8
from django.db import models

class BookInfoManager(models.Manager):
    # 自定义管理器:应用一  更改默认查询集
    def get_queryset(self):
        return super(BookInfoManager, self).get_queryset().filter(bread__gt=20)
    # 自定义管理器:应用二  扩展方法
    def create_book(self, btitle, bpub_date, bread):
        book = BookInfo()
        book.btitle = btitle
        book.bpub_date = bpub_date
        book.bread = bread
        book.save()
        return book

# 定义图书模型类BookInfo
class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)  # 图书名称
    bpub_date = models.DateField()  # 发布日期
    bread = models.IntegerField(default=0)  # 阅读量
    bcommet = models.IntegerField(default=0)  # 评论量
    isDelete = models.BooleanField(default=False)  # 逻辑删除

    # 创建自定义管理器
    book = models.Manager()
    book2 = BookInfoManager()

    class Meta:  # 元信息类
        db_table = ‘bookinfo‘  # 指定表的名称

    def __str__(self):
        return self.btitle  # 打印时显示名称

# 定义英雄模型类HeroInfo
class HeroInfo(models.Model):
    hname = models.CharField(max_length=20)  # 英雄姓名
    hgender = models.BooleanField(default=True)  # 英雄性别
    isDelete = models.BooleanField(default=False)  # 逻辑删除
    hcontent = models.CharField(max_length=100)  # 英雄描述信息
    hbook = models.ForeignKey(‘BookInfo‘)  # 英雄与图书表的关系为一对多,所以属性定义在英雄模型中

    def __str__(self):
        return self.hname

视图views.py中

关键代码

def add(requst):
    book = BookInfo.book2.create_book("天龙八部2", date(2010, 1, 1), 60)

    return HttpResponse("<a href=‘/‘>首页</a>")

完整代码

from datetime import date
from django.shortcuts import render
from django.http import HttpResponse
from .models import *


# Create your views here.
def index(request):
    # return HttpResponse("ok")
    # context = {‘title‘: "django1", "list": range(10)}
    # blist=BookInfo.book.all()
    blist = BookInfo.book2.all()
    context = {‘blist‘: blist}
    return render(request, "booktest/index.html", context)


def add(requst):
    # 添加对象
    # book = BookInfo()
    # book.btitle = "流星蝴蝶剑"
    # book.bpub_date = date(2017, 10, 1)
    # book.bread = 30
    # book.save()
    book = BookInfo.book2.create_book("天龙八部2", date(2010, 1, 1), 60)

    return HttpResponse("<a href=‘/‘>首页</a>")


def list(request):
    ‘‘‘
    列出所有的图书信息
    ‘‘‘
    # 查询所有图书对象
    blist = BookInfo.objects.all()
    # 构造上下文,用于传递数据给模板
    context = {‘list‘: blist}
    # 调用模板
    return render(request, ‘booktest/list.html‘, context)
    pass


def detail(request, id):
    ‘‘‘
    列出编号为id的图书,所有英雄信息
    ‘‘‘
    # 根据图书编号查询图书对象
    book = BookInfo.objects.get(pk=id)
    # 构造上下文,将图书对象数据传递到模板
    context = {‘b‘: book}
    # 调用模板
    return render(request, ‘booktest/detail.html‘, context)

    pass

urls.py中

from django.conf.urls import include, url
from booktest import views

urlpatterns = [
    url(r‘^$‘, views.index),
    url(r‘^index/$‘, views.index),
    url(r‘^list/$‘, views.list),
    url(r‘^add/$‘, views.add),
    url(r‘^detail(\d+)/$‘, views.detail),
]

相关推荐