0

I'm tryng to create a set of objects from a POST request,in this I send the pk list of the objects that should be created:

data = { 'a_ref':["17629","17630","17631"] }
x= Model_Serializer(data=data)

this are my serializers:

class A_Serializer(serializers.ModelSerializer):
    class Meta:
        model = A
        fields = ('pk',)

class Model_Serializer(serializers.ModelSerializer):
    a_ref = A_Serializer( many=True)


    def create(self, validated_data):
        tracks_data = validated_data.pop('a_ref')
        model = Model.objects.create(**validated_data)

        for track_data in tracks_data:
            A.objects.create(ref=model, **track_data)
        return model

    class Meta:
        model = models.Model

but I get this:

[14]: x.is_valid()
Out[14]: False


x.errors
Out[16]: 
ReturnDict([
            ('a_ref',
             [{'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']},
              {'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']},
              {'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']}])])
Muhammad Hassan
  • 14,086
  • 7
  • 32
  • 54
user2239318
  • 2,578
  • 7
  • 28
  • 50
  • 1
    Check this one. https://stackoverflow.com/questions/47809551/how-to-update-multiple-records-at-once-bulk-update-in-django-api/47810186#47810186 – Anup Yadav Jan 23 '18 at 09:42

2 Answers2

0

As a_ref is a serializer, data to be send for this field should be list of objects. Just like this

data = {'a_ref':[
             {"pk": "17629"}, {"pk": "17630"},{"pk": "17631"}
        ]}
Muhammad Hassan
  • 14,086
  • 7
  • 32
  • 54
0

Does this work?

for track_data in tracks_data:
    temp_dict = {'pk':track_data}
    A.objects.create(ref=model, **temp_dict)
return model