Garrett Edel
Garrett Edel

Reputation: 110

How should I POST and serialize and array of arrays with DRF?

I'm having an issue POST-ing a JSON object that contains and array of arrays and deserializing it using Django Rest Framework.

The idea here is that there can be a dynamic number of players (players: 2) and a list of lists/array of arrays of weapons that the players have (player_weapons [[], []]).

//javascript on client
var post_data = {
    players: 2,
    player_weapons: [
        ["sword", "shield"],
        ["mace", "slingshot"],
    ]};

var results = jQuery.post( url, post_data );

#serializers.py
class GameSerializer(serializers.Serializer):
    players = serializers.IntegerField(min_value=1)
    player_weapons = serializers.ListField(
        child=serializers.ListField(
            child=serializers.CharField(min_length=1, allow_blank=True),
        min_length=0, 
        required=False),
    min_length=0, 
    required=False
)

The request.POST I get is:

<QueryDict: {'runs': ['1000'], 'additional_players': ['2'],
'player_weapons': ['sword,shield', 'mace,slingshot']}>

What's really weird is that when I do request.POST['player_weapons'] I get:

mace,slingshot

whereas I'm expecting/hoping to get:

[['sword', 'shield'], ['mace', 'slingshot']]

Any help on how I should be structuring the POST and handling it in DRF would be awesome.

Upvotes: 0

Views: 1028

Answers (1)

Garrett Edel
Garrett Edel

Reputation: 110

Thanks to RishiG for the help here.

Problem was that I wasn't specifying the contentType in the request. I slightly modified it to use jQuery's ajax request:

    var posting = jQuery.ajax({
        url: url,
        type: "POST",
        data: JSON.stringify(post_data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(){
        }
    });

Upvotes: 2

Related Questions