python / beginner
Snippet
Safe User Model Referencing
Using get_user_model() ensures that your code remains compatible with custom user models defined in the project settings.
snippet.py
python
1
2
3
4
5
6
7
from django.contrib.auth import get_user_model# Always use this to get the User classUser = get_user_model()def get_user_count():return User.objects.count()
django
Breakdown
1
from django.contrib.auth import get_user_model
Imports the helper that finds the currently active user model.
2
User = get_user_model()
Assigns the correct User class to a variable for use in your logic.