简体   繁体   English

如何在Django中序列化dict?

[英]How to serialize dict in Django?

I can't figure out how to serialize cleaned_data of some form. 我不知道如何序列化某种形式的cleaned_data The problem probably is, that this cleaned_data contains model objects . 问题可能是此cleaned_data包含model objects I didn't find anything touching this problem so I'm asking here. 我没有发现任何能解决这个问题的东西,所以我在这里问。

Exception Value: 异常值:
'dict' object has no attribute '_meta' 'dict'对象没有属性'_meta'

Is there some simple way or Django built-in function? 有一些简单的方法或Django内置函数吗?

My cleaned_data: 我的cleaned_data:

{'notes': u'dsads', 'language_from': <Language: Slovak>, 'file': None, 'short_description': u'dsadsad', 'text_to_translate': u'dsads', 'delivery_date': datetime.date(1930, 1, 1)}

This is a formset cleaned_data: 这是formset cleaned_data:

[{'language': <Language: Magyar>, 'level': <Level: Standard level>}, 
 {'language': <Language: Russian>, 'level': <Level: Standard level>}, {}, {}, {}]

serializer.serialize(cleaned_data) does not works because there are models inside the cleaned_data . serializer.serialize(cleaned_data)不起作用,因为在cleaned_data内部存在models

Only way I probably figured out is to change all objects to it's primary keys and after deserialize get them from the database. 我大概想出的唯一方法是将所有对象更改为其主键,然后在反序列化之后从数据库中获取它们。

I want to serialize cleaned_data because I sending them to another view. 我想序列化cleaned_data,因为我将它们发送到另一个视图。

The Django way to do this is to use model_to_dict . Django方法是使用model_to_dict This will serialize the model instance as a dictionary. 这会将模型实例序列化为字典。 Call this on each model instance respectively in you cleanded_data 在您cleanded_data每个模型实例上分别调用此cleanded_data

from django.forms.models import model_to_dict

model_to_dict(model_instance)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM