Reputation: 1853
I am trying to serialize my models with Django Rest framework - http://django-rest-framework.org/
This what I want is to serialize a model with ManyToMany relation in it:
class ImageResource(models.Model):
# Some code here
image = models.ImageField(upload_to=upload_images_to)
keywords = models.ManyToManyField('cards.Keyword', related_name='image_keywords', blank=True);
# More code here
So this is my model (I removed some of the fields to help you focus on the keywords field)
My seriallizer looks something like this:
class ImageResourceSerializer(serializers.HyperlinkedModelSerializer):
keywords = serializers.ManyRelatedField(source='keywords')
class Meta:
model = ImageResource
fields = ('id', 'url', 'image', 'keywords')
And the last thing that I will show is the result from the API
{
"id": 2,
"url": "http://127.0.0.1:3004/apiimageresource/2/",
"image": "images/1386508612-97_img-02.JPG",
"keywords": [
"birthday",
"cake"
]
},
As you see the keywords are returned as an array from strings (their names). My wish is to return them as a key value pair with their id and value:
"keywords": [
"1":"birthday",
"3":"cake"
]
If you know how to do this with my seriallizer I will be thankfull :)
Upvotes: 5
Views: 9789
Reputation: 15594
Create custom serializer:
class MyKeywordsField(serializers.RelatedField):
def to_native(self, value):
return { str(value.pk): value.name }
Use it:
class ImageResourceSerializer(serializers.HyperlinkedModelSerializer):
keywords = MyKeywordsField(many=True)
# ...
Upvotes: 6