Django でアップロードされたファイルから辞書を作成しました。
このディクショナリには、ネストされたディクショナリのリストがあります。
file = {"name": "filename", "sections": [{"section_name": "string", "lines": [{line_number: 0, "line"; "data"}]}], "etc": "etc"}
モデルは辞書の深さも表しています。
class Line(EmbeddedDocument):
line_number = IntField()
line = StringField()
definition = ReferenceField(Definition)
class Section(EmbeddedDocument):
section_name = StringField()
lines = EmbeddedDocumentListField(Line))
class File(Document):
name = StringField()
sections = EmbeddedDocumentListField(Section))
created_on = DateTimeField()
created_by = StringField()
modified_on = DateTimeField()
modified_by = StringField()
POSTでは、ファイルを上記の Dict に分割するために次のようにしています (ファイルは単純なテキスト ファイルです)。
file= {}
with open(os.path.join(path, filename + ".txt"), 'r') as temp_file:
filelines = temp_file.readlines()
sections = []
section = {}
lines = []
for i, l in enumerate(filelines):
if i == 0:
section["section_name"] = "Top"
elif '*' in l:
if l.index('*') == 0 and '*' not in lines[len(lines) - 2"line"]:
section["lines"] = lines
lines = []
sections.append(section)
section = dict()
section["section_name"] = filelines[i + 1][1:-2]
line = {"line_number": i + 1, "line": l}
lines.append(line)
section['lines'] = lines
sections.append(section)
file["name"] = filename
file["sections"] = sections
最後にこれを整理します。dict が作成されたら、シリアライザーを使用してどのようにシリアル化しますか?
これをシリアライザーに挿入することは可能ですか?
そうでない場合、どうすればすべてを検証してデータベースに入れることができますか?
私はそれらをシリアライザーに入れてみましjson.dumps()
たJsonRequst()
がdata=
、取得しましたUnable to get repr for <class '....'>
私は Django と MongoDB にかなり慣れていないので、さらに情報が必要な場合は提供できます :)
ありがとう!
アップデート
回答で提案されているように、モデルのリスト フィールドを EmbeddedDocumentListField に変更します。
回答済み
以下のBorisの提案のおかげで、最初は得られなかったエラーが指摘されました. タイプミスがあり、口述を直接FileSerializer(data=file)
作品に渡すのは魅力的でした! :)