mysqldjangopython-3.xyamlmysql5

Using Python 3/Django, how do I export MySql table data as a YAML file?


I'm using Python 3.7, Django 2.0 with MySql 5.7. I have an InnoDB table

mysql> show create table address_country;
+-----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table           | Create Table                                                                                                                                                                                                                                                                                        |
+-----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| address_country | CREATE TABLE `address_country` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) COLLATE utf8_bin NOT NULL,
  `code` varchar(2) COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=499 DEFAULT CHARSET=utf8 COLLATE=utf8_bin |
+-----------------+--------------------------------------------------------

How do I export the table data as a YAML file? I would preferably like to develop a solution that doesn't hard-code any of the MySql table name or columns but any solution is better than no solution at this point.


Solution

  • Django provides the dumpdata management command for just this purpose:

    python manage.py dumpdata address.Country --format yaml
    

    (This assumes the model is managed by Django. If it isn't you can still create an unmanaged model to reference the table, and then use this command).