django convert model instance to dict

前端 未结 1 1680
别那么骄傲
别那么骄傲 2021-02-13 17:40

I am a beginner in Django. And I need to convert Model instance in to dictionary similar as Model.objects.values do, with relation fields. So I write a little function to do thi

相关标签:
1条回答
  • 2021-02-13 18:12

    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
    )
    
    0 讨论(0)
提交回复
热议问题