给某张表的管理器重命名
class User(models.Model): name = models.CharField(max_length=100) people = models.Manager() 获取所有的queryset,用people替代objects obj = model.User.people.all()
重写管理器,增加或覆盖某些功能
class MyManager(models.Manager): def with_counts(self): from django.db import connection cursor = connection.cursor() cursor.execute("select name,count(1) from user group by name") result_list = [] for row in cursor.fetchall(): p = self.model(name=row[0]) p.count = row[1] result_list.append(p) return result_list class User(models.Model): name = models.CharField(max_length=100) sex = models.CharField(max_length=100) objects = MyManager() class Meta: db_table = 'user' #查询 obj = models.User.objects.with_counts() print obj[0].count # 1
重写manager.get_queryset()覆盖管理器自带的Queryset
get_queryset()会根据需要返回查询集
#增加一个只查询男性用户的管理器 class MaleUserManager(models.Model): def get_queryset(self): return super(MaleUserManager,self).get_queryset().filter(sex='male') class User(models.Model): name = models.CharField(max_length=100) sex = models.CharField(max_length=100) objects = models.Manager() male_objects = MaleUserManager() class Meta: db_table = 'user' #查询 可以使用 User.objects.all(),User.male_objects.all()