Skip to content

Instantly share code, notes, and snippets.

@alanhamlett
Created September 22, 2014 01:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alanhamlett/0d773566dcd9a3bc89bc to your computer and use it in GitHub Desktop.
Save alanhamlett/0d773566dcd9a3bc89bc to your computer and use it in GitHub Desktop.
django model manager example
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.db import models, transaction
from django.utils import timezone
class Manager(models.Manager):
""" Use this class to define custom methods on models.
"""
def get_query_set(self):
return QuerySet(self.model)
def __getattr__(self, name, *args):
if name.startswith('_'):
raise AttributeError
return getattr(self.get_query_set(), name, *args)
""" Custom QuerySet class to provide a first() method, which behaves like
get() except returns None instead of raising an exception.
"""
class QuerySet(models.query.QuerySet):
""" Use this class to define methods on QuerySet itself.
"""
def first(self, *args, **kwargs):
try:
return self.filter(*args, **kwargs)[0]
except IndexError:
return None
class UserManager(BaseUserManager):
def _create_user(self, email, first_name, last_name, password,
is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email).lower()
user = self.model(email=email,
first_name=first_name, last_name=last_name,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser, last_login=now,
**extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, first_name=None, last_name=None, password=None,
**extra_fields):
if not first_name:
first_name = u''
if not last_name:
last_name = u''
return self._create_user(email, first_name, last_name, password,
False, False, **extra_fields)
def create_superuser(self, email, first_name, last_name, password,
**extra_fields):
return self._create_user(email, first_name, last_name, password,
True, True, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
objects = UserManager()
USERNAME_FIELD = 'email'
email = models.EmailField(max_length=254, unique=True, db_index=True)
first_name = models.CharField(max_length=60)
last_name = models.CharField(max_length=60)
is_staff = models.BooleanField(default=False,
help_text='Designates whether the user can log into this admin '
'site.')
is_active = models.BooleanField(default=True,
help_text='Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.')
language = models.CharField(max_length=120, null=True)
timezone = models.CharField(max_length=120, null=True)
type = models.CharField(max_length=120, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class UserProfile(models.Model):
objects = Manager()
user = models.ForeignKey(User, unique=True)
birth_date = models.DateField(null=True)
gender = models.CharField(max_length=30, null=True)
updated_at = models.DateTimeField(auto_now=True)
# lazy create user profile on first access
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
@MrazTevin
Copy link

I tried the same using the django signals but i got an error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment