Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework Serialization of ManyRelatedField

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 :)

like image 789
valkirilov Avatar asked Dec 09 '13 12:12

valkirilov


People also ask

What is serialization in Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

How do you serialize a Manytomany field?

To serialize many to many field with Python Django rest framework, we can add a serializer with many set to True . to create the PostSerializer with the tag field assigned to the TagSerializer instance. We set many to true to let us serialize many to many fields.

Is serialization necessary in Django?

It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.

What is PrimaryKeyRelatedField in Django?

PrimaryKeyRelatedField. PrimaryKeyRelatedField may be used to represent the target of the relationship using its primary key. For example, the following serializer: class AlbumSerializer(serializers. ModelSerializer): tracks = serializers.


1 Answers

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)
    # ...
like image 122
mariodev Avatar answered Oct 14 '22 01:10

mariodev