Convert Django Model Instance to Dictionary with Foreign Instance Fields
To convert a Django model instance to a dictionary with foreign instance fields included, you can use the 'model_to_dict()' function from the 'django.forms.models' module.
Assuming you have a 'Post' model with a foreign key field 'author' pointing to a 'User' model, you can convert a 'Post' instance to a dictionary with the 'author' field included like this:
from django.forms.models import model_to_dict
from myapp.models import Post
post = Post.objects.get(pk=1)
post_dict = model_to_dict(post, fields=['id', 'title', 'content', 'author'])
post_dict['author'] = model_to_dict(post.author, fields=['id', 'username'])
In this example, we first convert the 'Post' instance to a dictionary using 'model_to_dict()' and specify the fields we want to include (i.e. 'id', 'title', 'content', and 'author'). Then, we manually add the 'author' field to the dictionary by converting the 'User' instance to a dictionary using 'model_to_dict()' and specifying the fields we want to include (i.e. 'id' and 'username').
原文地址: http://www.cveoy.top/t/topic/lMCo 著作权归作者所有。请勿转载和采集!