Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a Serializer for array data in REST API in Django Rest Framework?

I have written basic model serializers in Django where the api mimics the data model. I now have a requirement to store User Preference in database. The api contains an array.

My User Models :

class User(models.Model):
    email_id = models.EmailField(max_length=80, blank=True, primary_key=True)

class UserPreference(models.Model)
    email_id = models.ForeignKey('User')
    preference = models.CharField(maxlength=20)

An ideal json post request would look something like this

{
    email:"[email protected]"
    preference : [ 'books', 'food', 'lifestyle', 'travel']
}

I wish to save this json schema to the UserPreference model. This requires multiple inserts for preference. What will be a good serializer design for it ?

I tried

class UserPreferenceSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserPreference
        fields = ('email_id', 'preference')
like image 791
Abhishek Avatar asked Apr 06 '15 20:04

Abhishek


1 Answers

you could use StringRelatedField of Django Rest Framework.

Make below changes and you will get the response in the way you want.

models.py (put related_name there)

class UserPreference(models.Model):
    email_id = models.ForeignKey(User, related_name='preference')
    preference = models.CharField(maxlength=20)

serializers.py

class UserSerializer(serializers.ModelSerializer):
    preference = serializers.StringRelatedField(many=True)

    class Meta:
        model = User
        fields = ('email_id', 'preference')
like image 109
Zealous System Avatar answered Oct 16 '22 18:10

Zealous System