I'm using django's rest framework to show information about the user. Every user has some contacts that are saved in UserProfile (user profile uses a one-to-one relationship to use). The contacts can be accessed directly in the user model (user.contacts).
I want to display the name (and URL) for all contacts of a user. I wrote the following serializer:
class ContactsUserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ("username", "email")
class ContactsSerializer(serializers.ModelSerializer):
# user = ContactsUserSerializer(many=True) # raises TypeError: 'User' object is not iterable
class Meta:
model = UserProfile
fields = ("user",)
class UserSerializer(serializers.HyperlinkedModelSerializer):
contacts = ContactsSerializer(many=True)
class Meta:
model = get_user_model()
fields = ("url", "username", "email", "contacts")
which return
{
"url": "http:\/\/localhost:8080\/users\/1\/",
"username": "test1",
"email": "",
"contacts": [
{
"user": 2
},
{
"user": 1
}
]
}
but I want it to be:
{
"url": "http:\/\/localhost:8080\/users\/1\/",
"username": "test1",
"email": "",
"contacts": [
{
"url": "http://link_to_user",
"username": "foo"
},
{
"url": "http://link_to_user",
"username": "bar"
}
]
}
How can I achieve that? I already tried to add another serializer for the contact users but that raises a Type Error: 'User' object is not iterable and the JSON structure would look a little bit awkward: {contacts: [ user: {"username": ...},]}, which might confuse the user of the API if he isn't confident with Django's User Profile.