1

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?

7
  • that iterates through the interests and saves every single one, do you mean many2many relashion? or you just want save it as array? Commented May 5, 2018 at 20:59
  • @BearBrown I would prefer to have each item in interest stored as a single row in an interests database table, making it possible to filter the applications by them. However, isn't the relationship OneToMany? Or will duplicates be avoided? Commented May 5, 2018 at 21:03
  • if you use many_to_many the duplicates will be absent. Django generate unique index on both relation fields. Commented May 5, 2018 at 21:11
  • @BearBrown Just what I'd want. Does the ManyToMany field automatically iterate and store each item as its own row (as long as its not duplicate)? Commented May 5, 2018 at 21:14
  • read the docs please, i added link in the first comment. Commented May 5, 2018 at 21:22

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What does model = Parent mean in this case?
It is the name of fhe orm model we want to serialize

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.