我怎样才能将 Django 模型对象变成字典并且仍然有它们的外键? [英] How can I turn Django Model objects into a dictionary and still have their foreign keys?

查看:18
本文介绍了我怎样才能将 Django 模型对象变成字典并且仍然有它们的外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 模型对象变成字典并且仍然有它们的外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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