LoginSignup
4
5

More than 5 years have passed since last update.

django の dumpdata コマンドの代替

Last updated at Posted at 2013-11-09

django の manage.py dumpdata で出力される json が、日本語がエスケープされてしまったり、フィールド名がモデルの順番と違っていたりとイマイチだったので、代わりにインタラクティブを使ってこんな風にした。(モデル名とかは例のため実際とは変えてます)

>>> import json
>>> from collections import OrderedDict
>>> from django.core.serializers.json import DjangoJSONEncoder
>>> from account.models import User
>>> users = list(User.objects.all().order_by('id'))
>>> field_names = ["name", "birthday", "description"]
>>> a = [OrderedDict([("pk", user.pk), ("model", "account.user"), ("fields", OrderedDict([(name, getattr(user, name)) for name in field_names]))]) for user in users]
>>> print json.dumps(a, cls=DjangoJSONEncoder, indent=2)

ポイントは、

  • OrderedDict を json.dump すると順番が維持される
  • datetime を出力するためには cls=DjangoJSONEncoder が必要

という辺り。

フィールド名はモデルの属性から取れるはずなので、もっと汎用化することもできそう。

(追記)

日本語がエスケープされてしまったり

結局この問題は、一度出力されたものを Python 3 のシェルに貼り付ける等してアドホックに解決してる。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5