我是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"])
您可以提出更好的解决方案吗?谢谢! 附:抱歉我的英文。
答案 0 :(得分:18)
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
)