如何在Django中导入用户模型并选择所有对象

时间:2013-06-25 19:01:49

标签: django django-views django-rest-framework django-users

当我使用

from django.conf import settings

在我的DjangoRestFramework视图中,

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

我收到错误

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'

1 个答案:

答案 0 :(得分:7)

settings.AUTH_USER_MODEL是一个字符串。它不是模型对象。

你需要做这样的事情:

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()

现在,

queryset = User.objects.all()

- 或 -

如果你只使用django 1.5,你可以简单地做:

from django.contrib.auth import get_user_model

queryset = get_user_model().objects.all()