将Django Model对象转换为dict,所有字段都保持不变
如何将django Model对象转换为包含其所有字段的dict ?理想情况下,所有内容都包含外键和带有editable = False的字段。
让我详细说明一下。假设我有一个类似以下的django模型:
from django.db import modelsclass OtherModel(models.Model): passclass 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")
在终端中,我做了以下事情:
other_model = OtherModel()other_model.save()instance = SomeModel()instance.normal_value = 1instance.readonly_value = 2instance.foreign_key = other_model instance.save()instance.many_to_many.add(other_model)instance.save()
我想将其转换为以下字典:
{'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}