Home > Mobile >  Serialise an extended User Model in Django
Serialise an extended User Model in Django

Time:12-31

I'm extending a django auth user model in a Profile model:

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    activity = models.IntegerField(default=500)

    def _str_(self):
        return self

in my views I'm getting the current auth user and I get the associated profile:

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def getUserProfile(request):
    profile = Profile.objects.get(user = request.user)
    serializer = profileSerializer(profile, many=False)
    return Response(serializer.data)

Here is my serializers code:

from rest_framework import serializers
from .models import Profile

class profileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('first_name', 'activity')

The error I'm getting that Profie object has not a first_name attribute, but when I replace 'first_name' with 'user' I get only the id of the user, so I want to show the first_name as well.

Thank you

CodePudding user response:

The OneToOneField connects your field user in the Profile model to a User object which has a first_name attribute, but in the Profile table that user field is just a number that says which User object it is. To access the first name, you can do this:

from rest_framework import serializers
from .models import Profile

class profileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = '__all__'

Then in your template you could display the first_name like this, assuming you pass person to it where person is an instance of the Profile model:

{{ person.user.first_name }}

I also think it would be less confusing to use another name for the field, rather then user. Call it person maybe, like:

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    person = models.OneToOneField(User, on_delete=models.CASCADE)
    activity = models.IntegerField(default=500)

    def _str_(self):
        return self

CodePudding user response:

Try this:

from django.contrib.auth.models import User

class profileSerializer(serializers.ModelSerializer):
    first_name = serializers.CharField(max_length=200, read_only=True)

    class Meta:
        model = Profile
        fields = ('user', 'first_name', 'activity')

    def get_first_name(self, obj):
        return User.objects.filter(id=obj.user.id).first().values_list('first_name', flat=True).last()
  • Related