Search code examples
djangodjango-viewsdjango-rest-frameworkdjango-users

How can I import the user model in Django and select all of the objects


When I use

from django.conf import settings

in my DjangoRestFramework views,

class UserList(ListCreateAPIView):
    queryset = settings.AUTH_USER_MODEL.objects.all()
    serializer_class = UserSerializer

my I receive the error

AttributeError at /users/

'str' object has no attribute 'objects'

Request Method:     GET
Request URL:    http://localhost:9999/users/
Django Version:     1.5.1
Exception Type:     AttributeError
Exception Value:    

'str' object has no attribute 'objects'

Solution

  • settings.AUTH_USER_MODEL is a string. It is not a model object.

    You need to do something like this:

    try:
        from django.contrib.auth import get_user_model
    except ImportError: # django < 1.5
        from django.contrib.auth.models import User
    else:
        User = get_user_model()
    

    Now,

    queryset = User.objects.all()
    

    -- OR --

    if you are using only django 1.5, you can simply do:

    from django.contrib.auth import get_user_model
    
    queryset = get_user_model().objects.all()