简体   繁体   中英

How to deserialize an array of primary keys with Django Rest Framework PrimaryKeyRelatedField

I followed the docs when setting up my serializer.

class PlaylistSerializer(serializers.ModelSerializer):
    songs = serializers.PrimaryKeyRelatedField(queryset=Song.objects.all(), many=True, allow_empty=True, required=False)

    class Meta:
        model = Playlist
        fields = ['id', 'name', 'songs', 'created_at']

If I add a few songs to the playlist in the django admin and send a get request, I get the result I want.

{
    "id": 4,
    "name": "teszt3",
    "songs": [
        351,
        350
    ],
    "created_at": "2022-01-14T14:04:36.238350Z"
}

But I want to create or update a playlist with a similar list of primary keys of songs. If I send a POST request with this body:

{
    "name": "test2",
    "songs": [350, 351]
}

I get this error:

Incorrect type. Expected pk value, received str

If there's only one number (primary key) in the songs field, it works, but I want to create playlists with many songs at once. Is there a way to parse that array, or how could I solve this?

You probably have some error in your models or endpoint. Since you didn't provided that info, here is a working example that is fully compatible with your Serializer.

models.py

class Song(models.Model):
    pass


class Playlist(models.Model):
    name = models.CharField(max_length=50)
    songs = models.ManyToManyField(Song)
    created_at = models.DateTimeField(auto_now_add=True)

views.py

class CreatePlaylist(CreateAPIView):
    serializer_class = PlaylistSerializer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM