1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DjangoでPython DictionaryをTextFieldに突っ込んだ後でliteral_evalを使えば戻せてハッピー

Posted at
  1. DjangoでTextFieldにdictを突っ込む。
  2. 読み出す
  3. dictじゃなくてStringが返ってきて困る。
  4. ast.literal_eval()でオブジェクトに変換できる。
  5. 飯が美味い
  6. わざわざjson使わなくていい
  7. literal_eval() という単語が覚えにくいからメモ。
from ast import literal_eval

def some_handle(self):
    result = SomeAPIExecute()
    model = SomeModel.objects.get(id=1)

    model.column = result
    model.save() 


def some_view(self):
    model = SomeModel.objects.get(id=1)
    saved_result = model.column # 文字列になってしまう。
    response = literal_eval(saved_result) #  めでたしめでたし

    return response
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?