[Python] What's the difference between get_user_model() and importing CustomUser model...

Discussão em 'Python' iniciado por Stack, Junho 6, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página