How to serialize a user model in DRF

I created a user model by specifying tutorial , this is how I serialize a new user model:

Serializers.py

from django.conf import settings
User = settings.AUTH_USER_MODEL

class UserSerializer(serializers.ModelSerializer):
    post = serializers.PrimaryKeyRelatedField(many=True, queryset=Listing.objects.all())
    class Meta(object):
        model = User
        fields = ('username', 'email','post')

Views.py

from django.conf import settings
User = settings.AUTH_USER_MODEL
class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

But when I tried to use this serializer, I get

'str' object has no attribute '_meta'

What did I do wrong?

+4
source share
1 answer

Instead

User = settings.AUTH_USER_MODEL

using

from from django.contrib.auth import get_user_model
User = get_user_model()

Remember that settings.AUTH_USER_MODEL- this is just stringthat which indicates which user model you are using not the model itself. If you want to get a model, useget_user_model

+10
source

Source: https://habr.com/ru/post/1607891/


All Articles