Gjert
Gjert

Reputation: 1067

Serializing and storing JSON array in Django REST Framework

I'm trying to make a demo website for job applications using Angular 6 and Django Rest Framework. One of my application fields involve listing your interests in a chip input field like this one.

The JSON being sent to my API would look something like this:

{
    ...
    'firstname': 'Firstname',
    'lastname': 'Lastname'
    ...
    'interests': ['hobby1', 'hobby2', 'hobby3', 'hobby4'],
    ...
}

Now as far as I know Django REST Framework supplies a serializer field that is written something like this:

interests = serializers.ListField(
   item = serializers.CharField(min_value=xx, max_value=xx)
)

My question is, how do I proceed from here? What model fields do I use, or do I have to create my own save function that iterates through the interests and saves every single one?

Upvotes: 1

Views: 3331

Answers (1)

Josef Korbel
Josef Korbel

Reputation: 1208

Many to many relationship is the thing you are looking for.

You can even have nested serializer so the output of the parent objects would include the serialized interests in the JSON.

class ParentSerializer(serializers.ModelSerializer):
    child_set = ChildSerializer(many=True)
    class Meta:
        depth = 1
        model = Parent
        fields = ('id', 'other_atributes', 'child_set')

Also you can easily edit those relationship in Django Admin, can post a snippet of that also if you would be interested.

'interests': ['hobby1', 'hobby2', 'hobby3', 'hobby4']

This is basically valid JSON, so you can parse this easily on your end.

Upvotes: 2

Related Questions