django将模型实例转换为dict [英] django convert model instance to dict
本文介绍了django将模型实例转换为dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Django的初学者。而且我需要将Model实例转换为类似于Model.objects.values的字典,并带有关系字段。所以我写了一个小函数来做到这一点:
I am a beginner in Django. And I need to convert Model instance in to dictionary similar as Model.objects.values do, with relation fields. So I write a little function to do this:
def _get_proper(instance, field):
if field.__contains__("__"):
inst_name = field.split("__")[0]
new_inst = getattr(instance, inst_name)
next_field = "__".join(field.split("__")[1:])
value = _get_proper(new_inst, next_field)
else:
value = getattr(instance, field)
return value
def instance_to_dict(instance, fields):
return {key: _get_proper(instance, key) for key in fields}
因此,我可以这样使用它:
So, i can use it in such way:
user_obj = User.objects.select_related(...).get(...)
print instance_to_dict(user_obj, ["name", "city__name", "city_id"])
您可以提出更好的解决方案吗?谢谢!
P.S.抱歉,我的英文。
May you propose the better solution? Thanks! P.S. Sorry for my English.
推荐答案
from django.forms import model_to_dict
my_obj = User.objects.first()
model_to_dict(my_obj,
fields = [...], # fields to include
exclude = [...], # fields to exclude
)
这篇关于django将模型实例转换为dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文