Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize custom user model in DRF

I have made a custom user model,by referring the tutorial , this is how I serialize the 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?

like image 342
dev-jim Avatar asked Sep 17 '15 19:09

dev-jim


People also ask

What is serialization DRF?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

How do I serialize Queryset?

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is SlugRelatedField?

SlugRelatedField. SlugRelatedField may be used to represent the target of the relationship using a field on the target. For example, the following serializer: class AlbumSerializer(serializers. ModelSerializer): tracks = serializers.


1 Answers

Instead of

User = settings.AUTH_USER_MODEL

use

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

Remember that settings.AUTH_USER_MODEL is just a string that indicates which user model you will use not the model itself. If you want to get the model, use get_user_model

like image 152
levi Avatar answered Oct 14 '22 04:10

levi