如何使用 DjangoRestFramework 序列化为多个模型 [英] How to serialize into multiple models using DjangoRestFramework
问题描述
我已经定义了一个用户配置文件模型,但想要有一个 api 端点来将所有用户数据保存到两个模型中.我的意思是,我正在使用用户模型,并且我有一个定义如下的用户配置文件模型
I have defined a user profile model, but want to have one api endpoint that saves all of the user data into both models. By that I mean, I am using the user model and I have a userprofile model defined as follows
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
biography = models.TextField()
当我定义一个用于创建新用户的序列化程序时,如何让它将数据序列化到用户模型和 userProfile 模型中?
when I define a serializer for creating a new user, how do I get it to serialize data into both the user model, and the userProfile model?
推荐答案
你只需要为每一个定义一个序列化器,并将一个附加到另一个,如下:
You just need to define a serializer for each, and attach one to the other, as follows:
from rest_framework.serializers import ModelSerializer
class UserSerializer(ModelSerializer):
"""
A serializer for ``User``.
"""
class Meta(object):
model = User
class UserProfileSerializer(ModelSerializer):
"""
A serializer for ``UserProfile``.
"""
user = UserSerializer()
class Meta(object):
model = UserProfile
然后您可以使用 UserProfileSerializer
更新(或执行其他操作)用户配置文件及其用户实例.
You could then use UserProfileSerializer
to update (or perform other actions to) a user profile and its user instance.
这篇关于如何使用 DjangoRestFramework 序列化为多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!