相关疑难解决方法(0)

将Django Model对象转换为dict,所有字段都保持不变

如何将django Model对象转换为包含其所有字段的dict ?理想情况下,所有内容都包含外键和带有editable = False的字段.

让我详细说明一下.假设我有一个类似以下的django模型:

from django.db import models

class OtherModel(models.Model): pass

class SomeModel(models.Model):
    normal_value = models.IntegerField()
    readonly_value = models.IntegerField(editable=False)
    auto_now_add = models.DateTimeField(auto_now_add=True)
    foreign_key = models.ForeignKey(OtherModel, related_name="ref1")
    many_to_many = models.ManyToManyField(OtherModel, related_name="ref2")
Run Code Online (Sandbox Code Playgroud)

在终端中,我做了以下事情:

other_model = OtherModel()
other_model.save()
instance = SomeModel()
instance.normal_value = 1
instance.readonly_value = 2
instance.foreign_key = other_model
instance.save()
instance.many_to_many.add(other_model)
instance.save()
Run Code Online (Sandbox Code Playgroud)

我想将其转换为以下字典:

{'auto_now_add': datetime.datetime(2015, 3, 16, 21, 34, 14, 926738, tzinfo=<UTC>),
 'foreign_key': 1,
 'id': 1,
 'many_to_many': [1],
 'normal_value': 1,
 'readonly_value': 2}
Run Code Online (Sandbox Code Playgroud)

回答不满意的问题:

Django:将一整套Model的对象转换为单个字典

如何将Django Model对象转换为字典并仍然拥有其外键?

python django dictionary django-models

215
推荐指数
8
解决办法
14万
查看次数

标签 统计

dictionary ×1

django ×1

django-models ×1

python ×1