Home > Software design >  What's the difference between get_user_model() and importing CustomUser model directly?
What's the difference between get_user_model() and importing CustomUser model directly?

Time:09-22

This is my views.py in a API server running Django REST framework.

from rest_framework import generics

from users.models import CustomUser
from .serializers import CustomUserSerializer


class APIView(generics.ListAPIView):
    queryset = CustomUser.objects.all()
    serializer_class = CustomUserSerializer

This code works fine. However, when I google around, I discovered that the recommended way is to use get_user_model().

So, the proper views.py should look like this;

from rest_framework import generics

from django.contrib.auth import get_user_model
from .serializers import CustomUserSerializer


class APIView(generics.ListAPIView):
    queryset = get_user_model().objects.all()
    serializer_class = CustomUserSerializer

I tested and both code worked as I wanted. What is the difference between the 2 code? Is get_user_model() really better?

I am using django v4, python 3.9, django rest framework.

CodePudding user response:

According to the get_user_model source, not much.

The idea of get_user_model is to decouple the authentication from the actual model. The goal of django applications is to be independant parts. Using get_user_model, you ensure that he User objects you have contains all the fields of an Abstract user. You can then use the application in other projects without worrying about the actual User model implementation.

In the example you showed us, using get_user_model does not add decoupling since CustomUserSerializer is coupled to your implementation of a user model.

CodePudding user response:

For your project? No difference.

For a reusable project or library that should work with any user model? You'd need to use get_user_model because you couldn't even know what the import for the user model is.

  • Related