django model to dict
To convert a Django model to a dictionary, you can do the following:
- Import the model and the
model_to_dictfunction from thedjango.forms.modelsmodule:
from django.forms.models import model_to_dict
from your_app.models import YourModel
- Retrieve the model instance you want to convert to a dictionary:
my_model_instance = YourModel.objects.get(id=my_id)
- Call the
model_to_dictfunction on the model instance:
my_model_dict = model_to_dict(my_model_instance)
This will give you a dictionary that contains the fields and values of the model instance. Note that this dictionary will also include fields that are related to other models (e.g. foreign keys), and these related objects will be represented as dictionaries themselves. If you want to exclude certain fields from the dictionary, you can pass a exclude argument to the model_to_dict function:
my_model_dict = model_to_dict(my_model_instance, exclude=['field_name_to_exclude'])
``
原文地址: http://www.cveoy.top/t/topic/fHJ4 著作权归作者所有。请勿转载和采集!