I'm new to Django Rest Framework,running v. 3.5.4 (Django 1.10.6) and I have implemented a simple model (Test) and its ModelSerializer.
This model has a manyTomany relationship with another one, but this is not the problem right now. The thing is that I need to pass an array of ids from my ajax call, to add to my manytomany relationship.
Ajax call is like this:
data = {
address: 'foo'
owner: [1,2]
}
ajax = $.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function(res){
console.log(res)
},
error: function(error) {
console.log(error,'erro')
}
})
My view is like this:
class Test(APIView):
def post(self, request, format=None):
print(request.data)
print([(x,y) for x,y in request.data.items()])
serializer = TestSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
So, the print outputs from my view are the problem:
Output from print(request.data) is <QueryDict: {'address': ['foo'], 'owner[]': ['1', '2']}>
So far so good!
Output from print([(x,y) for x,y in request.data.items()]) is [('address', 'foo'), ('owner[]', '2')]
Whaaaaat?
So, the array became a string with the last item only. What happened?
Apart from that, the is.valid() method seems to erase the array. I made a custom create method in my serializer:
class TestSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
owner = OwnerSerializer(many=True)
class Meta:
model = Test
fields = ('id','address','owner')
def create(self, validated_data):
print(validated_data)
return none
Output from print is {'address': 'foo', 'owner': []} And no error raised!
So, what is going on here?
Thanks!