如何将Django Model对象转换成字典并仍然有外键? [英] How can I turn Django Model objects into a dictionary and still have their foreign keys?

查看:700
本文介绍了如何将Django Model对象转换成字典并仍然有外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django应用程序中,如何将模型中的对象转换为包含Model对象的外键引用的字典?

In my Django app, how can I turn objects from Models into a dictionary that includes the foreign-key references of the Model object?

当我尝试这样:

from django.forms.models import model_to_dict
model_to_dict(instance, fields=[], exclude=[])

结果字典只有直接字段。我也想得到与Model对象相关的外键。如何做到这一点?

The resulting dictionary only has the direct fields. I would like to also get the foreign keys related to the Model object. How can I do this?

推荐答案

obj = get_object_or_404(CustomModel,id=some_id)
my_dict = obj.__dict__

这篇关于如何将Django Model对象转换成字典并仍然有外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆