django orm 管理器 objects

給某張表的管理器重命名

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()會根據須要返回查詢集django

#增長一個只查詢男性用戶的管理器
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()
相關文章
相關標籤/搜索