如何将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")
在终端中,我做了以下工作:
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()
我想把它转换成下面的字典:
{'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}
回答不满意的问题:
Django: Converting an entire set of a Model's objects into a single dictionary
How can I turn Django Model objects into a dictionary and still have their foreign keys?
发布于 2021-03-09 23:48:52
当我尝试使用django-rest框架将django站点转换为API时,我遇到了这个问题。通常,django从数据库返回三种类型的对象。它们包括一个查询集、一个模型实例和一个分页器对象。在我的例子中,这些是需要转换的。
查询集
查询集就像django中的模型对象列表。下面是将其转换为字典的代码。
model_data=Model.object.all()# This returns a queryset object
model_to_dict=[model for model in model_data.values()]
return Response(model_to_dict,status=status.HTTP_200_OK)
模型实例
模型实例是模型的单个对象。
model_instance=Model.objects.get(pk=1)# This will return only a single model object
model_to_dict=model_to_dict(model_instance)
return Response(model_to_dict,status=status.HTTP_200_OK)
分页器对象
分页器对象是包含特定页面的模型对象的对象。
model_queryset=Model.objects.all()
paginator = Paginator(model_queryset, 10)
try:
selected_results = paginator.page(page)
except Exception:
selected_results=result
paginator_to_dict=list(selected_results.object_list.values())
return Response(selected_results,status=status.HTTP_200_OK)
至少我是这么解决的。
https://stackoverflow.com/questions/21925671
复制相似问题