ChristophLSA
ChristophLSA

Reputation: 175

Django REST Framework: change field names

My Django application provides readonly api access to the users of the site. I created a user profile model and use it in the serializer of the user model:

Model:

# + standard User Model

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    display_name = models.CharField(max_length=20, blank=True)

Serializer:

class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('display_name',)

class UserSerializer(serializers.HyperlinkedModelSerializer):
    userprofile_set = UserProfileSerializer(many=False, label='userprofile')

    class Meta:
        model = User
        fields = ('id', 'username', 'userprofile_set')

This works but the field userprofile_set looks ugly. Is it possible to change the field name?

Upvotes: 1

Views: 2854

Answers (2)

fixmycode
fixmycode

Reputation: 8506

To complement your answer, you can also make use of relationships' related names:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True, related_name='profiles')
    display_name = models.CharField(max_length=20, blank=True)

that way you can also use this in your code:

user = User.objects.last() #some user
user.profiles.all() #UserProfiles related to this user, in a queryset
user.profiles.last() #the last UserProfile instance related to this user.

May I recommend that you turn that ForeignKey into a OneToOneField? that way an user can have one and just one user profile, and you don't need to establish uniqueness:

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    display_name = models.CharField(max_length=20, blank=True)

Upvotes: 2

ChristophLSA
ChristophLSA

Reputation: 175

Oh, I can name the variable userprofile_set as I like. First I tested the name userprofile which conflicted. If I name the field profile it works. :)

class UserSerializer(serializers.HyperlinkedModelSerializer):
    profile = UserProfileSerializer(many=False, label='userprofile')

    class Meta:
        model = User
        fields = ('id', 'username', 'profile')

Upvotes: 1

Related Questions