from django.db import models
class Person(models.Model):
#...
people = models.Manager()
通過以上代碼之后
Person.objects 會(huì)產(chǎn)生一個(gè) AttributeError 異常, 但是Person.people.all() 將會(huì)提供一個(gè)所有的Person的列表.
自定義Manager罐呼,主要用于增加方法或者修改返回值
from django.db import models
class PollManager(models.Manager):
def with_counts(self):
from django.db import connection
with connection.cursor() as cursor:
cursor.execute("""
SELECT p.id, p.question, p.poll_date, COUNT(*)
FROM polls_opinionpoll p, polls_response r
WHERE p.id = r.poll_id
GROUP BY p.id, p.question, p.poll_date
ORDER BY p.poll_date DESC""")
result_list = []
for row in cursor.fetchall():
p = self.model(id=row[0], question=row[1], poll_date=row[2])
p.num_responses = row[3]
result_list.append(p)
return result_list
class OpinionPoll(models.Model):
question = models.CharField(max_length=200)
poll_date = models.DateField()
objects = PollManager()
class Response(models.Model):
poll = models.ForeignKey(OpinionPoll, on_delete=models.CASCADE)
person_name = models.CharField(max_length=50)
response = models.TextField()
以上示例中使用 OpinionPoll.objects.with_counts() 則會(huì)返回一個(gè)OpinionPoll objects列表包含 num_responses 屬性
修改manager初始的QuerrySet
Manager 的基礎(chǔ)QS返回的是所有的成員
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
Book.objects.all() 將會(huì)返回?cái)?shù)據(jù)庫中所有的書
你可以復(fù)寫Manager的基礎(chǔ)QS嚼沿,通過集成類析命,復(fù)寫Manager.get_queryset() 方法來返回一個(gè)QS但是包含其他所需要的屬性
下屬例子中Book有2個(gè)manager未玻,其中一個(gè)為最原始的manager畅厢,返回的是所有的書本信息列表委粉,
然后添加一個(gè)DahlBookManager, 用于過濾信息蓄愁,這樣的話用戶在使用的時(shí)候可以使用
Models.objetcs 或者 Models.OTHER_MANAGER來調(diào)用不同的manager的方法來返回特定的信息双炕。
# First, define the Manager subclass.
class DahlBookManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(author='Roald Dahl')
# Then hook it into the Book model explicitly.
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
objects = models.Manager()
# The default manager. 調(diào)用的時(shí)候就是Book.objects .all()
dahl_objects = DahlBookManager()
# The Dahl-specific manager., 調(diào)用的時(shí)候就是Book.dahl_objects .all()