How to pass manytomany PKs to post or put

3.9k Views Asked by At
class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.PrimaryKeyRelatedField(many=True, queryset=Track.objects.all(), )

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')

what is the format for adding multiple tracks

tracks is a manytomany field

tried array, comma separated but no luck

If I pass

track = "Track1"

where "Track1" is the primary key of Track 1

How to add ['Track1', 'Track2']

Actual code

class TreatmentTemplateSerializer(serializers.ModelSerializer):
    icds = serializers.PrimaryKeyRelatedField(read_only=False, many=True, queryset=ICD_10.objects.all())
    class Meta:
        model = Treatment_template



Screenshot 1

enter image description here

Postman supports array in above format??



Screenshot 2

enter image description here



Screenshot 3

enter image description here

1

There are 1 best solutions below

1
On

Sending plain JSON objects

I would suggest testing complex request data (including arrays or nested objects) by directly sending JSON rather than form-data or x-www-form-urlencoded. To do this click on raw and paste your JSON object there.

To get a well-formatted JSON object to start with I usually first issue a GET request for a resource that already exists. Then I can just copy the response, change the request method to PUT, click the raw button and paste the json. Then I can start modifying the object and test the endpoint.

In the example above, does the following work?

{
  "uuid": "the-long-uuid-here",
  "icds": [
    "A00",
    "A001"
  ]
}

Update: Put multiple m2m ids with x-www-form-urlencoded

As I wasn't completely happy with not providing an alternative I tested a bit more (with the latest Postman which looks differently).

You can pass multiple values using x-www-form-urlencoded. To do that, add multiple rows with the same label icds and one value at a time.

Notice that I tested it with an endpoint that provides books, which would be icds in your use case. The data in the screenshot will be transmitted as books=1&books=3&last_name=foobar which gets correctly picked up by the DRF endpoint.


Screenshot Postman

Posting with x-www-form-urlencoded