Models and databases 之五 Manager

2017-06-11  本文已影响71人  低吟浅唱1990

Manager是Django models提供的接口查询数据库的接口,每个Django模型中至少有一个Manager

class Manager

Django默认给每个model添加一个名为objects的Manager,如果想改变这个默认名的话可以用如下方法

from django.db import models
class Person(models.Model):
      people = models.Manager()

>>>Person.people.all()获取全部记录,如果用Person.objects.all()会报错

可以通过扩展的基类Manager的方式自定义一个Manager,可以添加额外的方法,修改Manager运行的QuerySet

Adding extra manager methods

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_response = 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(model.Model):
      poll = models.ForeignKey(OpinionPoll,on_detele=models.CASCADE)
      person_name = models.CharField(max_lenght=50)
      response = models.TextField()

调用OpinionPoll.objects.with_counts()返回一个list

Modifying a manager’s initial QuerySet

原始Manager的QuerySet会返回所有的object

from django.db import models
class Book(models.Model):
     title = models.CharField(max_lenght=100)
     author = models.CharField(max_length=50)
>>>调用 Book.objects.all() 将会返回所有的objects

可以重写Manager.get_queryset()方法,返回你需要的查询结果

class DahlBookManager(models.Manager):
      def get_queryset(self):
            return super(DahlBookManager,self).get_queryset().filter(author='Roald Dahl')

class Book(models.Model):
      title = models.CharField(max_length=100)
      author = models.CharField(max_length=50)
      objects = models.Manager()
      dahl_objects = DahlBookManager()
>>>当调用 Book. dahl_objects.all()方法时,返回Roald Dahl的书

上例中说明可以在一个model添加多个Manager

在多个Manager的情况下,第一个添加的Manager为默认Manager,可以通过Meta.default_manager_name来指定默认的Manager

Calling custom QuerySet methods from the manager

通过Manager调用自定义查询方法

class PersonQuerySet(models.QuerySet):
      def authors(self):
          return self.filter(role='A')
      def editors(self):
          return self.filter(role='E')
class PersonManager(model.Manager):
      def get_queryset(self):
             return PersonQuerySet(self.model,using=self._db)
      def authors(self):
            return self.get_queryset().authors()
      def editors(self):
            return self.get_queryset().editors()
class Person(models.Model):
      first_name = models.CharField(max_length=50)
      last_name = models.CharField(max_length=50)
      role = models.CharField(max_length=1, choices=(('A', _('Author')), ('E', _('Editor
,!'))))
      people = PersonManager()
>>>可以直接调用authors() and editors()得到相应的数据

也可以通过 QuerySet.as_manager() 来创建一个Manager

people = PersonQuerySet.as_manager()
>>>与上例中一样
注意QuerySet中方法的修饰,能不能当成Manager中使用
上一篇下一篇

猜你喜欢

热点阅读