[Django]-Django Rest Framework โ€“ User Profile in nested User

7๐Ÿ‘

โœ…

Your ContactsSerializer would need to be a HyperlikedModelSerializer in order for the url field to be automatically added. Since you need the url field to point to a different model, you would actually need to use a HyperlinkedRelatedField and add it as a custom field on the serializer.

class ContactsSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedRelatedField(view_name="user-detail", source="user")
    username = serializers.CharField(source="user.username")

    class Meta:
        model = UserProfile
        fields = ("url", "username", )

You can use the source parameter to a field to use a different field on the model than what is being displayed. In this case, we are using fields from the user relationship on the profile.

user-detail would be the default view name if you were using a router or followed the tutorial. You may need to adjust this to match your detail view name.

Leave a comment