自定义查询对象 - objects
1. 声明类EntryManager,继承自models.Manager
在EntryManager 中添加自定义函数
class EntryManager(models.Manager):
# parameter自定义参数列表,
def function_name(self,parameter)
pass
return ....
2. 使用 EntryManager 覆盖models 类中的objects
class Entry(models.Model):
objects = EntryManager()
例如: 添加自定义函数 查询TestUser表中有多少个用户
完整代码:
index/models.py
from django.db import models
# 声明自定义的 objects -继承 models.Manager
class UserManager(models.Manager):
# 添加自定义函数
def user_count(self):
return self.all().count()
# Create your models here.
class TestUser(models.Model):
# 使用 UserManager 覆盖当前的objects
objects = UserManager()
name = models.CharField(max_length=150)
age = models.IntegerField()
email = models.EmailField(default=True)
isActive = models.BooleanField(default=True)
index/views.py
from django.http import HttpResponse
from .models import *
# Create your views here
# 展示有多少个用户
def display_user(request):
count = TestUser.objects.user_count()
return HttpResponse(count)
index/urls.py
from django.urls import path
from .views import *
urlpatterns = [
# 显示总用户路由
# http://127.0.0.1:8000/usercount/
path('usercount/', display_user),
]
|