django 将模型实例转换为字典
django convert model instance to dict
我是 Django 的初学者。我需要将 Model 实例转换为类似于 Model.objects.values 的字典,并带有关系字段。所以我写了一个小函数来做到这一点:
def _get_proper(instance, field):
if field.__contains__("__"):
inst_name = field.split("__")[0]
new_inst = getattr(instance, inst_name)
next_field = "__".join(field.split("__")[1:])
value = _get_proper(new_inst, next_field)
else:
value = getattr(instance, field)
return value
def instance_to_dict(instance, fields):
return {key: _get_proper(instance, key) for key in fields}
所以,我可以这样使用它:
user_obj = User.objects.select_related(...).get(...)
print instance_to_dict(user_obj, ["name", "city__name", "city_id"])
您可以提出更好的解决方案吗?谢谢!
P.S。对不起我的英语。
This actually already exists in Django, but its not widely documented.
from django.forms import model_to_dict
my_obj = User.objects.first()
model_to_dict(my_obj,
fields = [...], # fields to include
exclude = [...], # fields to exclude
)
我是 Django 的初学者。我需要将 Model 实例转换为类似于 Model.objects.values 的字典,并带有关系字段。所以我写了一个小函数来做到这一点:
def _get_proper(instance, field):
if field.__contains__("__"):
inst_name = field.split("__")[0]
new_inst = getattr(instance, inst_name)
next_field = "__".join(field.split("__")[1:])
value = _get_proper(new_inst, next_field)
else:
value = getattr(instance, field)
return value
def instance_to_dict(instance, fields):
return {key: _get_proper(instance, key) for key in fields}
所以,我可以这样使用它:
user_obj = User.objects.select_related(...).get(...)
print instance_to_dict(user_obj, ["name", "city__name", "city_id"])
您可以提出更好的解决方案吗?谢谢! P.S。对不起我的英语。
This actually already exists in Django, but its not widely documented.
from django.forms import model_to_dict
my_obj = User.objects.first()
model_to_dict(my_obj,
fields = [...], # fields to include
exclude = [...], # fields to exclude
)