I have a Django model which has, as a foreign key, a field related to a User.
class Notification(models.Model):
sender = models.ForeignKey(User, null=True)
is_read = models.BooleanField(default=False)
I want my serializer to show both the id and name of the user for this model so it's like this:
{
"count": 45,
"next": null,
"previous": null,
"results": [
{
"id": 2,
"sender": {
"id": 2,
"name": "my_name",
}
"is_read": false,
}
]
}
But when I add a new notification I want to send only the user's id, like this:
$ curl -X POST http://127.0.0.1:8000/notifications/ -H "Content-Type: application/json" -d "{\"sender\":\"4\"}"
I tried using a hyperlink in my serializer:
class NotificationSenderSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'name')
class NotificationSerializer(serializers.ModelSerializer):
sender_name = serializers.NotificationSenderSerializer()
class Meta:
model = Notification
fields = ('id', 'sender', 'is_read')
But what happens is that, this way, I need to send both the id and the name of the user when posting a new notification.
$ curl -X POST http://127.0.0.1:8000/notifications/ -H "Content-Type: application/json" -d "{\"sender\": {\"id\": \"4\", \"name\":\"my_name\"} }"
How can I solve this problem so that I can create a notification with only the user id, but receive both the id and name back reading the list of notifications?