Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Custom Managers for User model

Tags:

python

django

How would I go about extending the default User model with custom managers?

My app has many user types that will be defined using the built-in Groups model. So a User might be a client, a staff member, and so on. It would be ideal to be able to do something like:

User.clients.filter(name='Test')

To get all clients with a name of Test. I know how to do this using custom managers for user-defined models, but I'm not sure how to go about doing it to the User model while still keeping all the baked-in goodies, at least short of modifying the django source code itself which is a no no....

like image 486
JoseJose Avatar asked Oct 29 '09 10:10

JoseJose


People also ask

What is a manager in Django?

A manager is an interface through which database query operations are provided to Django models. At least one <span class="pre">Manager</span> exists for every model in a Django application, objects is the default manager of every model that retrieves all objects in the database.

How to create a custom user model in Django?

There are two modern ways to create a custom user model in Django: AbstractUser and AbstractBaseUser. In both cases we can subclass them to extend existing functionality however AbstractBaseUser requires much, much more work.

How do I save a user in Django?

This is how django managers work. You can read docs here I also had problems saving the custom user model and it took me while to figure it our within the User class, so in order to save the new user you need to call the " objects " is the item that calls the UserManager class and is called a manager in django

What is the best way to authenticate a user in Django?

Django ships with a built-in User model for authentication and if you'd like a basic tutorial on how to implement log in, log out, sign up and so on see the Django Login and Logout tutorial for more. However, for a real-world project, the official Django documentation highly recommends using a custom user model instead.


1 Answers

Yes, you can add a custom manager directly to the User class. This is monkeypatching, and it does make your code less maintainable (someone trying to figure out your code may have no idea where the User class acquired that custom manager, or where they could look to find it). In this case it's relatively harmless, as you aren't actually overriding any existing behavior of the User class, just adding something new.

from django.contrib.auth.models import User
User.add_to_class('clients', ClientsManager())

If you're using Django 1.1+, you could also subclass User with a proxy model; doesn't affect the database but would allow you to attach extra managers without the monkeypatch.

like image 195
Carl Meyer Avatar answered Oct 17 '22 08:10

Carl Meyer