[Fixed]-Django REST – cannot create model with relationships

1👍

I assume your create method is in the PlayerDetailSerializer? Note that it takes the validated data as an argument, you’re passing the request.

Also, you have to pop the PlayerDetail “manually”, and create the model instance. Because you don’t do this, the dict is in the validated data as the Player is validated. Then pass the object key to the Player.objects.create method . I cannot explain it better than the documentation, but I’ll paste the create method from the documentation as I think that’s what you have to change.

def create(self, validated_data):
    tracks_data = validated_data.pop('tracks')
    album = Album.objects.create(**validated_data)
    for track_data in tracks_data:
        Track.objects.create(album=album, **track_data)
    return album

Please let me know if I misunderstood your problem, so i can edit this answer.

👤DA–

Leave a comment