一、基本概念
- objects是Manager类型的对象,定义在from django.db import models中
- 用于模型对象和数据库交互
二、使用方法
假设定义了一个名为Students的模型,当查询数据库时一般都是:
#返回一个queryset()
Students.objects.all()
但是当自定义管理器对象时:
stuobj = models.Manager()
Students.stuobj.all()
注意:一旦自定义管理器对象,默认的objects 就不再自动生成
当查询某些字段并不想要.这时候就可以自定义objects:
class studentManager(models.Manager):
def get_queryset(self):
return super(studentManager,self).get_queryset().filter(isDelete=False)
三、自定义管理器
- 继承自BaseUserManager类
- 实现两个方法
- create_user(self, …, password=None):传递参数包括USERNAME_FIELD和REQUIRED_FIELDS字段,password可不传
- create_superuser(self, …):同上,但password必须提供
BaseUserManager 提供的一些实用方法:
classmethod normalize_email(email)
get_by_natural_key(username):Retrieves a user instance using the contents of the field nominated by USERNAME_FIELD
make_random_password(length=10, allowed_chars=‘abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789’), 用给出的长度length和给出的allowed_chars返回一个随机的密码, 注意allowed_chars没有包含 i, l, I, 1 和 o, O, 0